簡體   English   中英

設置任意 Func<> 的參數

[英]Set parameter of any Func<>

我有一個 object 的任何 func 類型 func<>, Func<,>, func<,,>... 我想用一個常量值替換其中一個輸入參數。

例如:

object SetParameter<T>(object function, int index, T value){
    //I don't know how to code this.
}

Func<int, String, String> function = (a, b) => a.ToString() + b;
object objectFunction = function;
object newFunction = SetParameter<int>(objectFunction, 0, 5);
// Here the new function should be a Func<String, String> which value "(b) => function(5, b)"

我現在已經如何獲取生成的 function 的類型,但這並不能真正幫助我實現所需的行為:

private Type GetNewFunctionType<T>(object originalFunction, int index, T value)
{
    Type genericType = originalFunction.GetType();

    if (genericType.IsGenericType)
    {
        var types = genericType.GetGenericArguments().ToList();
        types.RemoveAt(index);
        Type genericTypeDefinition = genericType.GetGenericTypeDefinition();
        return genericTypeDefinition.MakeGenericType(types.ToArray());
    }

    throw new InvalidOperationException($"{nameof(originalFunction)} must be a generic type");
}

目前尚不清楚轉換的目的是什么,但避免所有反射不是更容易。 例如:

Func<int, string, string> func3 = (a, b) => a.ToString() + b;

Func<string, string> func3withConst = (b) => func3(10, b);

由於您談論的是非常有限的 scope (僅支持Func<TReturn>Func<T1, TReturn>Func<T1, T2, TReturn> )通過反射執行此操作更容易出錯且更難閱讀。

以防萬一您需要使用表達式樹來構建 function

object SetParameter<T>(object function, int index, T value)
{
    var parameterTypes = function.GetType().GetGenericArguments();

    // Skip where i == index
    var newFuncParameterTypes = parameterTypes.SkipWhile((_, i) => i == index).ToArray();

    // Let's assume function is Fun<,,> to make this example simple :)
    var newFuncType = typeof(Func<,>).MakeGenericType(newFuncParameterTypes);

    // Now build a new function using expression tree.
    var methodCallParameterTypes = parameterTypes.Reverse().Skip(1).Reverse().ToArray();
    var methodCallParameters = methodCallParameterTypes.Select(
        (t, i) => i == index
            ? (Expression)Expression.Constant(value, typeof(T))
            : Expression.Parameter(t, "b")
        ).ToArray();

    // func.Invoke(5, b)
    var callFunction = Expression.Invoke(
        Expression.Constant(function),
        methodCallParameters);

    // b => func.Invoke(5, b)
    var newFunc = Expression.Lambda(
        newFuncType,
        callFunction,
        methodCallParameters.OfType<ParameterExpression>()
    ).Compile();

    return newFunc;
}

要使用這個:

Func<int, string, string> func = (a, b) => a.ToString() + b;

var newFunc = (Func<string, string>)SetParameter<int>(func, 0, 5);

// Output: 5b
Console.WriteLine(newFunc("b"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM