转换函数功能< T,串>到Func键< T,BOOL>

转换函数功能< 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&gt MapFun<A,B,C&gt(Func<A,B&gt input, Func<B,C&gt 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&gt(this Func<A,B> input, Func<B,C> f)
    {
         return a => f(input(a));
    }
}

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

here is a very simple test:


Func<int, string&gt test = i =&gt 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)