表面上看,匿名方法是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。這個在以後的文章中再分別做詳細說明。