如何通过反射为参数的默认值调用方法的方法

如何通过反射为参数的默认值调用方法的方法

问题描述:

我必须通过默认值参数来调用方法.通过此消息,它具有 TargetParameterCountException :参数计数不匹配

I have need to invoke a method by default value parameters. It has a TargetParameterCountException by this message : Parameter count mismatch

var methodName = "MyMethod";
var params = new[] { "Param 1"};

var method = typeof(MyService).GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
method.Invoke(method.IsStatic ? null : this, params);

private void MyMethod(string param1, string param2 = null)
{
}

为什么?我该如何通过反射来调用此方法以获取参数的默认值?

Why? How can I invoke this method by reflection for default value for parameters?

您可以使用 ParameterInfo.DefaultValue 进行检测.您需要检查给定的参数数量是否等于方法中的参数数量,然后找到具有默认值的参数并提取这些默认值.

You can use ParameterInfo.HasDefaultValue and ParameterInfo.DefaultValue to detect this. You'd need to check whether the number of arguments you've been given is equal to the number of parameters in the method, and then find the ones with default values and extract those default values.

例如:

var parameters = method.GetParameters();
object[] args = new object[parameters.Length];
for (int i = 0; i < args.Length; i++)
{
    if (i < providedArgs.Length)
    {
        args[i] = providedArgs[i];
    }
    else if (parameters[i].HasDefaultValue)
    {
        args[i] = parameters[i].DefaultValue;
    }
    else
    {
        throw new ArgumentException("Not enough arguments provided");
    }
}
method.Invoke(method.IsStatic ? null : this, args);