1.LINQ是C#3中最闪亮的部分,扩展方法、lambda表达式、匿名类型等新的语法基本上都是围绕着为LINQ服务而诞生的。搞清楚这些语法对我们熟悉和掌握LINQ非常有帮助。其中,lambda表达式其实就是匿名的delegate。自己写了一个很小的demo,用来体现普通代理、匿名方法代理以及lambda表达式之间的关系。
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using EagleFish.CommonLib;
6
7 namespace CommonConsoleProject
8 {
9 delegate TResult GenericDelegateFunc<TArg, TResult>(TArg arg);
10
11 class Program
12 {
13 public static bool SomeMethod(int _arg)
14 {
15 return _arg > 0;
16 }
17
18 static void Main(string[] args)
19 {
20 GenericDelegateFunc<int, bool> func = new GenericDelegateFunc<int, bool>(SomeMethod);
21
22 //the use of Anonymous method, from C#2.0
23 GenericDelegateFunc<int, bool> funcUseAnonymousMethod = delegate(int arg)
24 {
25 return arg > 0;
26 };
27
28 //the use of Anonymous delegate(lambda expression),from C# 3.0
29 GenericDelegateFunc<int, bool> funcUseAnonymousDele = x => {
30 Console.WriteLine("Now in the body of a lambda expression");
31 return x > 0;
32 };
33
34
35 Console.WriteLine(func(3));
36 Console.WriteLine(funcUseAnonymousMethod(5));
37 Console.WriteLine(funcUseAnonymousDele(-6));
38
39 Console.Read();
40 }
41 }
42 }
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using EagleFish.CommonLib;
6
7 namespace CommonConsoleProject
8 {
9 delegate TResult GenericDelegateFunc<TArg, TResult>(TArg arg);
10
11 class Program
12 {
13 public static bool SomeMethod(int _arg)
14 {
15 return _arg > 0;
16 }
17
18 static void Main(string[] args)
19 {
20 GenericDelegateFunc<int, bool> func = new GenericDelegateFunc<int, bool>(SomeMethod);
21
22 //the use of Anonymous method, from C#2.0
23 GenericDelegateFunc<int, bool> funcUseAnonymousMethod = delegate(int arg)
24 {
25 return arg > 0;
26 };
27
28 //the use of Anonymous delegate(lambda expression),from C# 3.0
29 GenericDelegateFunc<int, bool> funcUseAnonymousDele = x => {
30 Console.WriteLine("Now in the body of a lambda expression");
31 return x > 0;
32 };
33
34
35 Console.WriteLine(func(3));
36 Console.WriteLine(funcUseAnonymousMethod(5));
37 Console.WriteLine(funcUseAnonymousDele(-6));
38
39 Console.Read();
40 }
41 }
42 }
由于C# 3的这些新特性都是对C#编译器的改进,并不涉及对IL的修改,所以有心的同学可以通过ILDasm看到这些代理的实现方式。