我有一个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,5);
// Here the new function should be a Func<String,String> which value "(b) => function(5,b)"
我现在已经如何获取结果函数的类型,但这并不能真正帮助我实现所需的行为:
private Type GetNewFunctionType<T>(object originalFunction,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");
}