泛型委托Action与ActionT

以前都是自己写委托,其实系统内部给我们系统了委托的。

Action ——委托的非泛型版本就是一个无参数无返回值的委托。

Action<T>——委托的泛型版本是一个无返回值,但是参数个数及类型可以改变的委托。 

Func<T>——委托只有泛型版本的,接受参数个数可以是若干个,也可以没有参数,但是一定要有返回值

  class Program
    {
        //定义委托
        //public delegate void adddelegate();
        static void Main(string[] args)
        {
            //【1】使用自己定义的委托
            //adddelegate my = add;
            //if (my!=null)
            //{
            //  my();
            //}
            //【2】使用系统委托
            Action my = add;
            if (my!=null)
            {
                my.Invoke();
            }
            Console.ReadKey();
        }

        static void add()
        {

            Console.WriteLine("你好世界");
        }
    }

泛型委托

  数据类型可以改变的委托

理解:比如你要写一个有参数string类型的委托那你就需要定义一个string参数类型的委托,我这个类型又要变成int,你还要写个int参数的委托那是bool的还要写个bool的委托

这个样很麻烦。泛型委托因此而生。

 class Program
    {
        //定义泛型委托
        public delegate void PrintDelegate<T>(T str);
        static void Main(string[] args)
        {
            //根据泛型委托来接收方法
            PrintDelegate<int> my2 = add2;
            //给泛型委托传递参数
            my2.Invoke(365);
            PrintDelegate<string> my = add;
       
my("?");
      //使用系统Action<>泛型委托
       Action <string> my3=add;
        //使用多个参数的泛型Action委托
     
  Action<int, string> my4 = add2;

        my4.Invoke(365,"中国");

       my3("??");
            
            Console.ReadKey();
        }
        static void add(string a)
        {

            Console.WriteLine("你好世界"+a);
        }
        static void add2(int a)
        {

            Console.WriteLine("你好世界" + a);
        }
    }

猜你喜欢

转载自www.cnblogs.com/xiaowie/p/9391048.html
今日推荐