简体   繁体   中英

How invoke method for a method by default value for parameters by reflection

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?

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.

For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM