C#委托

2019-10-31  本文已影响0人  ZHAnGtiAnwen

Delegate 至少 0 个参数,至多 32 个参数,可以无返回值,也可以指定返回值类型
Func 可以接受 0 个至 16 个传入参数,必须具有返回值 Func表示无参,返回值int的函数,Func(object,int) object类型参数,int返回值类型
Action 可以接受 0 个至 16 个传入参数,无返回值 Action<int,string> 表示传入int和string类型的参数
Predicate 只能接受一个传入参数,返回值为 bool 类型

namespace Test
{
    public delegate int del(int a);    //声明常用委托

    class Program
    {
        //delegate组合
        public static int Combine1(int a)
        {
            Console.WriteLine(a);
            return a + 1;
        }
        public static int Combine2(int a)
        {
            Console.WriteLine(a);
            return a + 2;
        }

        //Func 有返回值 参数可有可无的内置委托
        public static int Aaa(int a)
        {
            return a;
        }

        //Action无返回值 参数可有可无的内置委托
        public static void Action1(int s)
        {
            Console.WriteLine(s);
        }
        public static void Test<T>(Action<T> action, T p)
        {
            action(p);
        }

        static void Main(string[] args)
        {

            Test<int>(Action1, 234);   //需定义Action1函数

            Test<string>(r =>
            {             //Lambda函数省略定义函数  r是内部自定义临时变量 
                Console.WriteLine("{0}", r);
            }, "Lambda Action");

            Func<int, int> funccc = Aaa;      //Func 有返回值 
            Console.WriteLine(funccc(1234));

            del d = Combine1;    //声明委托变量并赋值
            d += Combine2;        //委托合并,组合
            Console.WriteLine(d(1));

            Console.ReadKey();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读