2

首先, foo 是一个 Func<T1,T2,TResult> 对象。有可能做类似的事情

Func<T2,T1,TResult> bar = ConvertFunction(foo);

因此将 Func<T1,T2,TResult> 转换为 Func<T2,T1,TResult>。

4

2 回答 2

7

是的,这是可能的:

Func<T2, T1, TResult> bar = (t2, t1) => foo(t1, t2);

这基本上创建了另一个具有切换参数的委托,该委托在内部简单地调用原始委托。如果您只有 a而不是 a ,
这是执行这种“转换”的唯一方法Func<T1, T2, TResult>Expression<Func<T1, T2, TResult>>

于 2013-02-21T08:03:52.693 回答
0

这是功能:

class MyFuncConverter<T1, T2, TResult>
{
    static Func<T1, T2, TResult> _foo;

    public static Func<T2, T1, TResult> ConvertFunction(Func<T1, T2, TResult> foo)
    {
        _foo = foo;
        return new Func<T2, T1, TResult>(MyFunc);
    }

    private static TResult MyFunc(T2 arg2, T1 arg1)
    {
        return _foo(arg1, arg2);
    }
}

示例用法:

static void Main(string[] args)
{
    var arg1 = 10;
    var arg2 = "abc";

    // create a Func with parameters in reversed order 
    Func<string, int, string> testStringInt = 
        MyFuncConverter<int, string, string>.ConvertFunction(TestIntString);

    var result1 = TestIntString(arg1, arg2);
    var result2 = testStringInt(arg2, arg1);

    // testing results
    Console.WriteLine(result1 == result2);
}

/// <summary>
/// Sample method
/// </summary>
private static string TestIntString(int arg1, string arg2)
{
    byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII
        .GetBytes(arg2.ToString() + arg1);
    string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
    return returnValue;
}
于 2013-02-21T08:17:41.423 回答