Jon*_*eet 48
简单:
Func<string,bool> func = x => x.Length > 5;
Predicate<string> predicate = new Predicate<string>(func);
Run Code Online (Sandbox Code Playgroud)
基本上,您可以使用任何兼容的现有实例创建新的委托实例.这也支持方差(共同和反对):
Action<object> actOnObject = x => Console.WriteLine(x);
Action<string> actOnString = new Action<string>(actOnObject);
Func<string> returnsString = () => "hi";
Func<object> returnsObject = new Func<object>(returnsString);
Run Code Online (Sandbox Code Playgroud)
如果你想让它通用:
static Predicate<T> ConvertToPredicate<T>(Func<T, bool> func)
{
return new Predicate<T>(func);
}
Run Code Online (Sandbox Code Playgroud)
Geo*_*uer 10
我懂了:
Func<object, bool> testLambda = x=>true;
int idx = myList.FindIndex(x => testLambda(x));
Run Code Online (Sandbox Code Playgroud)
工作,但ick.
我玩游戏有点晚了,但我喜欢扩展方法:
public static class FuncHelper
{
public static Predicate<T> ToPredicate<T>(this Func<T,bool> f)
{
return x => f(x);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
List<int> list = new List<int> { 1, 3, 4, 5, 7, 9 };
Func<int, bool> isEvenFunc = x => x % 2 == 0;
var index = list.FindIndex(isEvenFunc.ToPredicate());
Run Code Online (Sandbox Code Playgroud)
嗯,我现在看到了 FindIndex 扩展方法。我猜这是一个更一般的答案。与 ConvertToPredicate 也没有太大区别。
| 归档时间: |
|
| 查看次数: |
14636 次 |
| 最近记录: |