Lor*_*nVS 25
假设你有一个如下功能:
private static string toLower(string s)
{
return s.ToLower();
}
Run Code Online (Sandbox Code Playgroud)
System.Func有一个版本,它带有两个泛型参数,第一个是第一个参数的类型,第二个是返回类型.因此,您可以写:
Func<string,string> myFunction = toLower;
string s = myFunction("AsDf");
// s is now "asdf"
Run Code Online (Sandbox Code Playgroud)
在所有版本的System.Func中,最后一个泛型参数是返回类型,其他所有参数都是参数的类型.
System.Func很有用,因为它不需要您编写自定义委托类型.这使得使用相同签名交互代理变得更加容易.
说我有:
public delegate string MyDelegate1(string s);
public delegate string MyDelegate2(string s);
MyDelegate1 myDel = new MyDelegate1(toLower); // toLower as above
Run Code Online (Sandbox Code Playgroud)
现在无法将MyDelegate1委托转换为MyDelegate2类型的对象,即使它们具有相同的方法签名.另一方面,如果我们使用Func而不是声明自定义委托类型,我们就不会遇到这个问题
System.Func<T>通常用作另一个函数的参数.它可以是返回值T的任何委托 - 并且有多个版本可用作具有多个参数的委托.
一种常见的用法是过滤 - 例如,在LINQ中,您可以传递一个函数以用作Enumerable.Where函数中的过滤器,以限制集合.例如:
public bool FilterByName(string value)
{
return value.StartsWith("R");
}
// .. later
List<string> strings = new List<string> { "Reed", "Fred", "Sam" };
var stringsStartingWithR = strings.Where(FilterByName);
Run Code Online (Sandbox Code Playgroud)
但是,在上面的例子中,你更有可能使用lambda表达式来动态构建Func<string,bool>,如下所示:
var stringsStartingWithR = strings.Where(s => s.StartsWith("R"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21757 次 |
| 最近记录: |