Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 260
Ehsan Avatar asked Dec 24 '13 11:12

Ehsan


People also ask

What invoke () method do in C#?

This method dynamically invokes the method reflected by this instance on obj , and passes along the specified parameters. If the method is static, the obj parameter is ignored. For non-static methods, obj should be an instance of a class that inherits or declares the method and must be the same type as this class.

What is the use of Invoke method?

The invoke () method of Method class Invokes the underlying method represented by this Method object, on the specified object with the specified parameters. Individual parameters automatically to match primitive formal parameters.

What is reflection in programming C#?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.


1 Answers

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);
like image 195
Jon Skeet Avatar answered Nov 14 '22 23:11

Jon Skeet