以下內(nèi)容為菩提樹下的楊過根據(jù)微軟MSDN整理,轉(zhuǎn)貼請注明出處
MSDN對于Func<T, TResult>)的官方解釋:
封裝一個具有一個參數(shù)并返回 TResult 參數(shù)指定的類型值的方法。
下面通過幾個例子對比下,就容易知道其用法:
以下例子演示了如何利用委托將字符串轉(zhuǎn)化為大寫:
delegate string ConvertMethod(string inString);

private static string UppercaseString(string inputString)

...{
return inputString.ToUpper();
}

protected void Page_Load(object sender, EventArgs e)

...{
//ConvertMethod convertMeth = UppercaseString; 也可以這樣寫
ConvertMethod convertMeth = new ConvertMethod(ppercaseString);
string name = "Dakota";
Response.Write(convertMeth(name));//通過委托調(diào)用UppercaseString方法
}

這段代碼很容易理解,定義一個方法UppercaseString,功能很簡單:將字符串轉(zhuǎn)化為大寫,然后定義一個ConvertMethod的實(shí)例來調(diào)用這個方法,最后將Dakota轉(zhuǎn)化為大寫輸出
接下來改進(jìn)一下,將Page_Load中的 ConvertMethod convertMeth = new ConvertMethod(ppercaseString)改為Func 泛型委托,即:
protected void Page_Load(object sender, EventArgs e)

...{
Func<string, string> convertMeth = UppercaseString;
string name = "Dakota";
Response.Write(convertMeth(name));

}

運(yùn)行后,與前一種寫法結(jié)果完全相同,這里再聯(lián)系官方解釋想一想,F(xiàn)unc<string, string>即為封閉一個string類型的參數(shù),并返回string類型值的方法
當(dāng)然,我們還可以利用匿名委托,將這段代碼寫得更簡潔:
protected void Page_Load(object sender, EventArgs e)

...{

Func<string, string> convertMeth = delegate(string s) ...{ return s.ToUpper(); };
string name = "Dakota";
Response.Write(convertMeth(name));
}

怎么樣?是不是清爽很多了,但這并不是最簡潔的寫法,如果利用Lambda表達(dá)式,還可以再簡化:
protected void Page_Load(object sender, EventArgs e)

...{
Func<string, string> convertMeth = s => s.ToUpper();
string name = "Dakota";
Response.Write(convertMeth(name));
}
現(xiàn)在應(yīng)該體會到什么叫“代碼的優(yōu)雅和簡潔”了吧? 記起了曾經(jīng)學(xué)delphi時,一位牛人的預(yù)言:以后可能會出現(xiàn)一種新學(xué)科:程序美學(xué)! 對此,我深信不疑:優(yōu)秀的代碼就是一種美!
在linq to sql中其實(shí)大量使用了Func<T, TResult>這一泛型委托,下面的例子是不是會覺得很熟悉:
protected void Page_Load(object sender, EventArgs e)

...{
Func<string, string> convertMeth = str => str.ToUpper();

string[] words = ...{ "orange", "apple", "Article", "elephant" };
IEnumerable<String> aWords = words.Select(convertMeth);
foreach (String s in aWords)

...{
Response.Write(s + "<br/>");
}
}