如何转换 Func<T, bool>谓词<T>? [英] How to convert Func<T, bool> to Predicate<T>?

查看:41
本文介绍了如何转换 Func<T, bool>谓词<T>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,我看过这个,但我看不到找到我的具体问题的答案.

Yes I've seen this but I couldn't find the answer to my specific question.

给定一个 lambda testLambda,它接受 T 并返回一个布尔值(我可以将它设为 Predicate 或 Func,这取决于我)

Given a lambda testLambda that takes T and returns a boolean (I can make it either Predicate or Func that's up to me)

我需要能够同时使用 List.FindIndex(testLambda)(采用 Predicate)和 List.Where(testLambda)(采用 Func).

I need to be able to use both List.FindIndex(testLambda) (takes a Predicate) and List.Where(testLambda) (takes a Func).

有什么想法可以同时做到吗?

Any ideas how to do both?

推荐答案

简单:

Func<string,bool> func = x => x.Length > 5;
Predicate<string> predicate = new Predicate<string>(func);

基本上,您可以使用任何兼容现有实例创建一个新的委托实例.这也支持方差(co-和contra-):

Basically you can create a new delegate instance with any compatible existing instance. This also supports variance (co- and contra-):

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);
}

这篇关于如何转换 Func&lt;T, bool&gt;谓词&lt;T&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆