转换函数功能< T,串>到Func键< T,BOOL> [英] Convert Func<T, String> to Func<T, bool>

查看:114
本文介绍了转换函数功能< T,串>到Func键< T,BOOL>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我的心是爆炸试图找出funcs中......如果这是没有意义的,我很抱歉,现在它是有意义的我,但它是一个漫长的一天已经...

I think my mind is exploding trying to figure out Funcs... If this makes no sense, I apologize, right now it make sense to me but its been a long day already ....

1)假设您将得到一个FUNC这需要在T和输出的字符串:

1) Assuming you are given a func which takes in T and outputs a string:

 Func<T, string> 

您可以改变这种成参加一个T和返回一个布尔值基于某种逻辑FUNC(在这种情况下,如果返回的字符串是空的(String.IsNullOrWhiteSpace)

Can you transform that into a func that take in a T and returns a bool based on some logic (in this case if the returned string is empty (String.IsNullOrWhiteSpace)?

 Func<T, bool> 

2)你可以做同样的事情,如果你将得到一个

2) Can you do the same thing if you are given an

Expression<Func<T, string>>

和需要将其转换为

Func<T, bool>

这将返回真/假的基础上,如果返回的字符串是空的(String.IsNullOrWhiteSpace)?

that returns true/false based on if the returned string is empty (String.IsNullOrWhiteSpace)?

感谢

推荐答案

在第一部分,你甚至可以做一些高阶功能:

for the first part you can even make some "higher"-order function:



Func<A,C> MapFun<A,B,C>(Func<A,B> input, Func<B,C> transf)
{
   return a => transf(input(a));
}



use with



Func <T,string> test = ...
var result = MapFun(test, String.IsNullOrWhiteSpace);



(我希望C#类型类型推断这里工作)

(I hope C# type type inference is working here)

如果你定义了这个扩展的函数功能它变得更加容易:

If you define this as extension on Func it gets even easier:


public static class FuncExtension
{
    public static Func<A,C> ComposeWith<A,B,C>(this Func<A,B> input, Func<B,C> f)
    {
         return a => f(input(a));
    }
}

下面是一个非常简单的测试:

here is a very simple test:


Func<int, string> test = i => i.ToString();
var result = test.ComposeWith(string.IsNullOrEmpty);

有关第二个:我想你可以编译表达成真正的FUNC,然后用上面的代码。 看到Expression.Compile

For the second one: I think you can compile the expression into a "real" Func and then use the above code. see MSDN Docs on Expression.Compile

PS:改名的功能,以更好地匹配它的打算(它的功能组成)

PS: renamed the function to better match it's intend (it's function composition)

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

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