Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke a method with optional params via reflection [duplicate]

I can use Type.InvokeMember to invoke a method via reflection, and it seems pretty robust, dealing with param array parameters for example. For some reason however it doesn't deal with optional parameters.

Is there any better built in approach for invoking a method (perhaps using the DLR) that does take into account optional parameters?

like image 848
James Gaunt Avatar asked Apr 02 '12 13:04

James Gaunt


1 Answers

In following example, we are calling a function with two parameter that return nothing. Second param is optional.

MethodInfo mi = default(MethodInfo);

// Loading the assembly  
Assembly reflectionAssemby = Assembly.LoadFile(@"C:\RelectionDLL.dll");

// Get type of class from loaded assembly 
Type reflectionClassType = reflectionAssemby.GetType("ReflectionDLL.ReflectionClass");

// Create instance of the class 
object objReflection = Activator.CreateInstance(reflectionClassType);

mi = reflectionClassType.GetMethod("pub_Inst_NoReturn_Function");
mi.Invoke(objReflection, new object[] { value1, Type.Missing });
like image 134
Romil Kumar Jain Avatar answered Sep 30 '22 19:09

Romil Kumar Jain