是否可以将Func<;T1、T2、TResult>;到Func<;T2、T1、TResult>;

本文关键字:T1 T2 gt TResult lt Func 是否 | 更新日期: 2023-09-27 18:00:25

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

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

从而将Func<T1、T2、TResult>到Func<T2、T1、TResult>。

是否可以将Func<;T1、T2、TResult>;到Func<;T2、T1、TResult>;

是的,有可能:

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

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

下面是函数:

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;
}