以下内容为菩提树下的杨过根据微软MSDN整理,转贴请注明出处
MSDN对于Func<T, TResult>)的官方解释:
封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。
下面通过几个例子对比下,就容易知道其用法:
以下例子演示了如何利用委托将字符串转化为大写:
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));//通过委托调用UppercaseString方法
}
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));//通过委托调用UppercaseString方法
}
这段代码很容易理解,定义一个方法UppercaseString,功能很简单:将字符串转化为大写,然后定义一个ConvertMethod的实例来调用这个方法,最后将Dakota转化为大写输出
接下来改进一下,将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));
}
{
Func<string, string> convertMeth = UppercaseString;
string name = "Dakota";
Response.Write(convertMeth(name));
}
运行后,与前一种写法结果完全相同,这里再联系官方解释想一想,Func<string, string>即为封闭一个string类型的参数,并返回string类型值的方法
当然,我们还可以利用匿名委托,将这段代码写得更简洁:
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));
}
{
Func<string, string> convertMeth = delegate(string s) { return s.ToUpper(); };
string name = "Dakota";
Response.Write(convertMeth(name));
}
怎么样?是不是清爽很多了,但这并不是最简洁的写法,如果利用Lambda表达式,还可以再简化:
protected void Page_Load(object sender, EventArgs e)
{
Func<string, string> convertMeth = s => s.ToUpper();
string name = "Dakota";
Response.Write(convertMeth(name));
}
{
Func<string, string> convertMeth = s => s.ToUpper();
string name = "Dakota";
Response.Write(convertMeth(name));
}
现在应该体会到什么叫“代码的优雅和简洁”了吧? 记起了曾经学delphi时,一位牛人的预言:以后可能会出现一种新学科:程序美学! 对此,我深信不疑:优秀的代码就是一种美!
在linq to sql中其实大量使用了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/>");
}
}
{
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/>");
}
}