まず、foo は Func<T1,T2,TResult> オブジェクトです。次のようなことは可能ですか
Func<T2,T1,TResult> bar = ConvertFunction(foo);
したがって、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;
}