Inferring generic types with functional composition

前端 未结 4 1593
猫巷女王i
猫巷女王i 2021-01-05 18:04

Suppose I want to implement a functional composition, like this:

    public Func Compose(Func f, Func g)
    {
            


        
相关标签:
4条回答
  • 2021-01-05 18:18

    Adding to lasseespeholt's answer, if you define Compose as an extension method (renamed "Then" so that the result makes more sense):

    public static Func<T, T> Then<T>(this Func<T, T> f, Func<T, T> g)
    {
        return x => g(f(x));
    }
    

    you can make this fluent:

    var h = toUpper.Then(replicate); // .Then(trim) etc...
    
    0 讨论(0)
  • 2021-01-05 18:31

    The following code would work:

    Func<string, string> toUpper = ToUpper;
    Func<string, string> replicate = Replicate;
    
    // now the compiler knows that the parameters are Func<string, string>
    var h = Compose(toUpper, replicate);
    

    So maybe you can still get the readability improvement you are seeking by defining those variables only once and them reusing them throughout your tests (I'm assuming this is a test utility...)

    0 讨论(0)
  • 2021-01-05 18:31

    You could pass Compose the parameter too, and have it actually evaluate the function; it should be able to infer the parameter type in that case. (You might need to still specify the return type, though.)

    Other than that, no, there's no way to infer things like this in C#.

    0 讨论(0)
  • 2021-01-05 18:39

    I like Ran´s answer (+1), but I think this make it a little more concise and nice. (Works under the assumption that you have the possibility to redefine the functions as follows.)

    Func<string, string> toUpper = s => s.ToUpper();
    Func<string, string> replicate = s => s + s;
    
    var h = Compose(toUpper, replicate);
    
    0 讨论(0)
提交回复
热议问题