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);
See more on this question at Stackoverflow