C#方法代理/委托(delegate)用法介绍和示例

先决条件:C#中的代理(委托,delegate)
创建自定义委托时, 我们必须遵循以下步骤:
第1步:用与该方法完全相同的格式声明一个自定义委托。
第2步:创建自定义委托的对象。
第三步:调用方法。
通过使用这些步骤, 我们创建了一个自定义委托, 如下面的程序所示。但是问题在于, 要创建委托, 我们需要遵循上述过程。为了克服这种情况, C#提供了一个内置委托, 该委托功能。使用Func委托, 你无需遵循以下过程即可创建委托。
例子:

//C# program to illustrate how to //create custom delegates using System; class GFG {//Declaring the delegate public delegate int my_delegate( int s, int d, int f, int g); //Method public static int mymethod( int s, int d, int f, int g) { return s * d * f * g; }//Main method static public void Main() {//Creating object of my_delegate my_delegate obj = mymethod; Console.WriteLine(obj(12, 34, 35, 34)); } }

输出如下:
485520

【C#方法代理/委托(delegate)用法介绍和示例】Func是内置的泛型类型委托。该委托使你不必像上面的示例中那样定义自定义委托, 并使程序更具可读性和优化性。众所周知, Func是泛型委托, 因此在系统命名空间。它可以包含最小0和最大16个输入参数在里面仅包含一个out参数。的Func委托的最后一个参数是out参数, 它被视为返回类型并用于结果。 Func通常用于将要返回值的那些方法, 换句话说, Func委托用于值返回的方法。它也可以包含相同类型或不同类型的参数。
语法如下:
//零个普通参数和一个结果参数公共委托TResult Func < out PResult> (); //一个普通参数和一个结果参数公共委托TResult Func < in P, out PResult> (P arg); //两个普通参数和一个结果参数公共委托TResult Func < in P1, in P2, out PResult> (P1 arg1, P2 arg2); //十六个普通参数和一个结果参数公共委托TResult Func < 在P1, P2, P3, P4, P05, P6, P7, P8, P9, P10, P11, P12, 在P13中, 在P14中, 在P15中, 在P16中, 输出PResult> (P1 arg1, P2 arg2, P3 arg3, P4 arg4, P5 arg5, P6 arg6, P7 arg7, P8 arg8, P9 arg9, P10 arg10, P11 arg11, P12 arg12, P13 arg13, P14 arg14, P15 arg15, P16 arg16);
这里, P1, P2…。P16是输入参数的类型, 结果是输出参数的类型, 并且arg1…。arg16是Func委托封装的方法的参数。
示例1:在这里, 我们使用Func委托仅在一行中创建委托, 而无需使用上述过程。该Func委托包含四个输入参数和一个输出参数。
//C# program to illustrate Func delegate using System; class GFG {//Method public static int mymethod( int s, int d, int f, int g) { return s * d * f * g; }//Main method static public void Main() {//Using Func delegate //Here, Func delegate contains //the four parameters of int type //one result parameter of int type Func< int , int , int , int , int> val = mymethod; Console.WriteLine(val(10, 100, 1000, 1)); } }

输出如下:
1000000

示例2:
//C# program to illustrate Func delegate using System; class GFG {//Method public static int method( int num) { return num + num; }//Main method static public void Main() {//Using Func delegate //Here, Func delegate contains //the one parameters of int type //one result parameter of int type Func< int , int> myfun = method; Console.WriteLine(myfun(10)); } }

输出如下:
20

重要事项:
Func Delegate中的最后一个参数始终是out参数, 该参数被视为返回类型。通常用于结果。
你还可以将Func委托与匿名方法一起使用。如下例所示:
例子:
Func< int , int , int> val = delegate ( int x, int y, int z) { return x + y + z; };

你还可以将Func委托与lambda表达式一起使用。如下例所示:
例子:
Func< int , int , int , int> val = ( int x, int y, int z) => x + y + z;

    推荐阅读