15.9 匿名方法

匿名方法在本质上是一个传递给委托的代码块,它是使用委托的另一种方法。匿名方法的最大优势在于其减少了系统开销,方法仅在委托使用时才定义。在大多数情况下,我们并不希望声明一个仅作为参数传递给委托的独立方法。此时,直接给委托传递一段代码要比先创建一个方法后再把该方法传递给委托简单得多。

使用匿名方法需要遵守如下规则:

❑匿名方法中不能使用跳转语句跳至此匿名方法的外部,反之亦然;匿名方法外部的跳转语句也不能跳到此匿名方法的内部。

❑在匿名方法内部不能访问不安全的代码。另外,也不能访问在匿名方法外部定义的ref和out参数。但可以使用在匿名方法外部定义的其他变量。

接下来是一个简单的匿名方法的例子。

代码清单15-8 匿名方法


1 namespace ProgrammingCSharp4

2{

3//委托类型

4 public delegate void PrintDelegate();

5

6 public class DelegateSample

7{

8 public static void Main()

9{

10//匿名方法

11 PrintDelegate pd=delegate

12{

13 System.Console.WriteLine("Printing……");

14};

15 pd();

16

17}

18}

19}


上述代码的输出结果为:


Printing……


当然,你也可以在匿名方法中返回计算结果,如代码清单15-9所示。

代码清单15-9 在匿名方法中返回值


1 namespace ProgrammingCSharp4

2{

3//委托类型

4 public delegate int PrintDelegate();

5

6 public class DelegateSample

7{

8 public static void Main()

9{

10//匿名方法

11 PrintDelegate pd=delegate

12{

13 System.Console.WriteLine("Printing……");

14 return 10;

15};

16 int result=pd();

17 System.Console.WriteLine("Completed!Total:{0}",result);

18}

19}

20}


上述代码的运行结果为:


Printing……

Completed!Total:10


可以像一般的委托那样,给匿名方法定义一个参数列表,以允许参数传递到匿名方法内部,如代码清单15-10所示。

代码清单15-10 带有参数列表的匿名方法示例


1 namespace ProgrammingCSharp4

2{

3//委托类型

4 public delegate void PrintDelegate(string content,bool isA4Paper);

5

6 public class DelegateSample

7{

8 public static void Main()

9{

10//匿名方法

11 PrintDelegate pd=delegate(string content,bool isA4Paper)

12{

13 System.Console.WriteLine("Printing……");

14 System.Console.WriteLine("The Content is:{0}",content);

15 System.Console.WriteLine("Is A4 Paper:{0}",isA4Paper);

16};

17 pd("The quick brown fox jumps oyer a lazy dog.",true);

18}

19}

20}


上述代码的运行结果为:


Printing……

The Content is:The quick brown fox jumps oyer a lazy dog.

Is A4 Paper:True