首页 > 学院 > 开发设计 > 正文

委托, 泛型委托,Func<T>和Action<T>

2019-11-17 02:29:26
字体:
来源:转载
供稿:网友

委托, 泛型委托,Func<T>和Action<T>

使用委托来做一些事情,大致思路是:

1、定义声明一个委托,规定输入参数和输出类型。2、写几个符合委托定义的方法。3、把方法列表赋值给委托4、执行委托

    internal delegate int MyDelegate();
    class PRogram
    {
        static void Main(string[] args)
        {
            MyDelegate d = ReturnOne;
            d += ReturnTwo;
            foreach (int i in GetAllReturnVals(d))
            {
                Console.WriteLine(i);
            }
            Console.ReadKey();
        }
        static IEnumerable<int> GetAllReturnVals(MyDelegate myDelegate)
        {
            foreach (MyDelegate del in myDelegate.GetInvocationList())
            {
                yield return del();
            }
        }
        static int ReturnOne()
        {
            return 1;
        }
        static int ReturnTwo()
        {
            return 2;
        }
    }

以上,委托的返回类型是int,如果让返回类型是泛型呢?只要让以上的GetAllReturnVals方法针对泛型就可以了。

   internal delegate T MyDelegate<T>();
    class Program
    {
        static void Main(string[] args)
        {
            MyDelegate<int> d = ReturnOne;
            d += ReturnTwo;
            foreach (int i in GetAllReturnVals(d))
            {
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表