C# 匿名办法
咱们曾经提到过,委托是用于援用与其具备雷同标签的办法。换句话说,您能够应用委托对象调用可由委托援用的办法。
匿名办法(Anonymous methods) 提供了一种传递代码块作为委托参数的技术。匿名办法是没有名称只有主体的办法。
在匿名办法中您不须要指定返回类型,它是从办法主体内的 return 语句推断的。
大题目
编写匿名办法的语法
匿名办法是通过应用 delegate 关键字创立委托实例来申明的。例如:
delegate void NumberChanger(int n); ... NumberChanger nc = delegate(int x) { Console.WriteLine("Anonymous Method: {0}", x); };
代码块 Console.WriteLine("Anonymous Method: {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); } static void Main(string[] args) { // 应用匿名办法创立委托实例 NumberChanger nc = delegate(int x) { Console.WriteLine("Anonymous Method: {0}", x); }; // 应用匿名办法调用委托 nc(10); // 应用命名办法实例化委托 nc = new NumberChanger(AddNum); // 应用命名办法调用委托 nc(5); // 应用另一个命名办法实例化委托 nc = new NumberChanger(MultNum); // 应用命名办法调用委托 nc(2); Console.ReadKey(); } }}
当下面的代码被编译和执行时,它会产生下列后果:
Anonymous Method: 10
Named Method: 15
Named Method: 30