是的,我见过this https://stackoverflow.com/questions/665494/c-why-funct-bool-instead-of-predicatet但我找不到我的具体问题的答案。
给定一个 lambda测试Lambda接受 T 并返回一个布尔值(我可以将其设为 Predicate 或 Func,这取决于我)
我需要能够使用 List.FindIndex(testLambda) (采用谓词)和 List.Where(testLambda) (采用 Func)。
有什么想法如何做到这两点吗?
Easy:
Func<string,bool> func = x => x.Length > 5;
Predicate<string> predicate = new Predicate<string>(func);
基本上你可以用任何创建一个新的委托实例兼容的现有实例。这也支持方差(同向和反向):
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);
如果你想让它通用:
static Predicate<T> ConvertToPredicate<T>(Func<T, bool> func)
{
return new Predicate<T>(func);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)