如何转换函数功能< T,布尔>以predicate< T>? [英] How to convert Func<T, bool> to Predicate<T>?

查看:251
本文介绍了如何转换函数功能< T,布尔>以predicate< T>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,我已经看到了但我找不到答案,我的具体的问题。

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

由于一个lambda testLambda 这需要T和返回一个布尔值(我可以使它无论是predicate或函数功能即是给我)

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).

任何想法如何做到既?

推荐答案

简单:

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

基本上,你可以创建任何的兼容的现有实例中一个新委托实例。这也支持差异(合作和反 - ):

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

这篇关于如何转换函数功能&LT; T,布尔&GT;以predicate&LT; T&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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