开发者

Converting between Func with different # of type args

Are there built in methods for converting between the various types of Func delegates? That is, suppose you need a Func, but you have a Func (and you have the value that should be passed in for the T parameter). For example:

static TREsult Foo<TResult>(Func<TResult> f)
{
   // ...
   TResult result = f();
   // ...
   return result;
}

static int MyFunc(int i)
{
    return i;
}

void CallFoo()
{
    Func<int> func = ConvertFunc(MyFunc, 1); // Does this family of methods exist?
    int j = Foo(func);
}

I've written my own, like this:

开发者_C百科
    static Func<TResult> ConvertFunc<T, TResult>(Func<T, TResult> f1, T t)
    {
        return () => f1(t);
    }

    static Func<TResult> ConvertFunc<T1, T2, TResult>(Func<T1, T2, TResult> f2, T1 t1, T2 t2)
    {
        return () => f2(t1, t2);
    }

    // etc.

But I'm wondering if a family of methods like this exists (or even if there's a better way to do this).

Essentially, I'm doing this for a case where there is some boiler plate code in a method followed by a function call (where the number and types in the function will vary, but the return type is the same), followed by more boiler plate code.

All opinions welcome! Thanks.


static Func<TResult> ConvertFunc<T, TResult>(Func<T, TResult> f1, T t)
{
    return () => f1(t);
}

This kind of code to me looks a bit dangerous - not that by itself is anything wrong but need to be careful. You are using closure to embed an input variable in the function. But this could lead to difficult bugs since if the variable changes between converting Func and running it, the result would be different.

I am just curious what would be the benefit. Are you trying to hide away input parameter from the consumer of the function? As long as the variable is a local one passed to it, would be fine.

In terms of a solution, there would not be one since .NET has created 16 different generic Func<> exactly for the same reason.

You can perhaps use reflection to implement a solution but you would be paying a penalty for calling the functions. MethodInfo.GetGenericArguments() would give you the types and you then can use MethodInfo.MakeGenericMethod() to create new ones.


Update

Just to illustrate my point:

    static int Double(int number)
    {
        return number * 2;
    }

    static void Main(string[] args)
    {

        int i = 2;
        Func<int> f = () => Double(i);
        i = 3;
        Console.WriteLine(f()); // prints 6 and not 4

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜