dimanche 19 avril 2020

Set parameter of any Func<>

I have an object of any of the func types func<>, Func<,>, func<,,> ... And I'd like to replace one of the input parameters with a constant value.

eg:

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)"

I already now how to get the type of the resulting function, but that does not really help me in implementing the desired behavior:

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




Aucun commentaire:

Enregistrer un commentaire