Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
938 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...