表面上看,匿名方法是C#2.0的一个新特性,但是本质上和1.0的delegate有很密切的关系,可以认为是delegate的升级版。当然,到了C#3.0有进一步升级,变成了lambda表达式,其表现形式越来越简洁。可以看出来C#语言的一个进化方向就是不断地去贴近人的思维,简化代码编写的逻辑,精简代码量。下面先看一个例子:
class Test
{
delegate void TestDelegate(string s);
static void M(string s)
{
Console.WriteLine(s);
}
static void Main(string[] args)
{
// Original delegate syntax required
// initialization with a named method.
TestDelegate testdelA = new TestDelegate(M);
// C# 2.0: A delegate can be initialized with
// inline code, called an "anonymous method." This
// method takes a string as an input parameter.
TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };
// C# 3.0. A delegate can be initialized with
// a lambda expression. The lambda also takes a string
// as an input parameter (x). The type of x is inferred by the compiler.
TestDelegate testDelC = (x) => { Console.WriteLine(x); };
// Invoke the delegates.
testdelA("Hello. My name is M and I write lines.");
testDelB("That's nothing. I'm anonymous and ");
testDelC("I'm a famous author.");
// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/* Output:
Hello. My name is M and I write lines.
That's nothing. I'm anonymous and
I'm a famous author.
Press any key to exit.
*/
可以看出来,匿名方法采用了一种内联的方式,封装了delegate的实现。这样做的好处是,当我们需要一个简单的delegate实体对象时,不必像以前一样,声明一个delegate的变量,并且将其绑定到一个方法。例如我们点击一个button,编写click响应事件函数,其实我们一般很少去直接调用button_click函数,因此没必要写着么繁杂的代码。
当然,不足之处也是显而易见的,就是当我们需要处理比较复杂的逻辑时,这种内敛的方式就会使的代码显得冗长,这个时侯还是用delegate的表达方式要好。
最后看看lambda表达式。它需要编写的代码量就更少了:(参数列表)=>{表达式},但是请注意,这些技术背后的原理都是一样的。当然,要了解lambda,我们还需要了解表达式树和LINQ。这个在以后的文章中再分别做详细说明。