新彩天欢迎您!
幻海优品

C# - 匿名方法

我们讨论了委托用于引用与委托具有相同签名的任何方法.换句话说,您可以使用该委托对象调用委托可以引用的方法.

匿名方法提供了一种将代码块传递为委托参数.匿名方法是没有名称的方法,只是正文.

您不需要在匿名方法中指定返回类型;它是从方法体内的return语句中推断出来的.

编写匿名方法

通过创建委托实例声明匿名方法,使用委托关键字.例如,

delegate void NumberChanger(int n);...NumberChanger nc = delegate(int x) {   Console.WriteLine("Anonymous Method: {0}", x);};

代码块 Console.WriteLine("匿名方法:{0}",x); 是匿名的主体方法.

可以使用匿名方法和命名方法以相同的方式调用委托,即通过将方法参数传递给委托对象.

例如,

nc(10);

示例

以下示例演示了概念 :

using System;delegate void NumberChanger(int n);namespace DelegateAppl {   class TestDelegate {      static int num = 10;            public static void AddNum(int p) {         num += p;         Console.WriteLine("Named Method: {0}", num);      }      public static void MultNum(int q) {         num *= q;         Console.WriteLine("Named Method: {0}", num);      }      public static int getNum() {         return num;      }      static void Main(string[] args) {         //create delegate instances using anonymous method         NumberChanger nc = delegate(int x) {            Console.WriteLine("Anonymous Method: {0}", x);         };                  //calling the delegate using the anonymous method          nc(10);                  //instantiating the delegate using the named methods          nc =  new NumberChanger(AddNum);                  //calling the delegate using the named methods          nc(5);                  //instantiating the delegate using another named methods          nc =  new NumberChanger(MultNum);                  //calling the delegate using the named methods          nc(2);         Console.ReadKey();      }   }}

编译并执行上述代码时,会产生以下结果 :

Anonymous Method: 10Named Method: 15Named Method: 30

免责声明:以上内容(如有图片或视频亦包括在内)有转载其他网站资源,如有侵权请联系删除