2019-02-25Action委托和Func委托

再c#中系统给我们提供过来了一个内置的委托类型,Action和Func委托。

Action委托引用了一个void返回类型的方法,T表示方法参数

Action

Action<in T>

Action<in T1, inT2>

Action<in T1,in T2 ... in T16>

Func引用了一个带有一个返回值的方法,他可以传递0或者多到16个参数类型,和一个返回类型。

Func<out TResult>

Func<in T,out TResult>

Func<in T1,in T2 ... in T16,out TResult>

Action委托示例1:

有一个参数:

        static void printstring(int i)
        {
            Console.WriteLine(i);
        }
       
        static void Main(string[] args)
        {
            Action<int> a = printstring;
            a(10);
        }  

          

Action委托示例2:

有多个参数:


        static void printIntString(int i2, string str1, int i3, string str2)
        {
            Console.WriteLine($"{str1}={i2}{str2}={i3}");
        }
        static void Main(string[] args)
        {
            Action<int,string,int,string> b = printIntString;
            b(10, "a", 20, "b");
            Console.ReadKey();
        }

Func委托示例1:

        static int test(int a, int b)
        {
            return a + b;
        }
        static void Main(string[] args)
        {
            Func<int, int, int> f = test;
            f(3, 6);
            Console.ReadKey();
        }

猜你喜欢

转载自blog.csdn.net/qq_31726339/article/details/87914618