I have a problem with reflection, basically i need to call a method of Class like this:
public Int32 addNumer (Int32 a, Int32 b)
{
return (a+b);
}
And i need to call it with Reflection, because i receive this input from “external” C#
software and i need to evaluate witch method i need to call.
The problem is that as Input i have 2 object passed by “prompt command line”,
o I have converted it in Byte:
Byte a = 10;
Byte b = 10;
So, when i perform Refection i see an error “cannot find method addNumber”
because the method with 2 byte in input was not found. I think that it expected
2 Int32 and not 2 Byte.
How i can resolve it?
D.
UPDATE 1:
Object result_object = target_class.InvokeMember(method,
BindingFlags.InvokeMethod, null, target_object,
args_values, null, null, args_names);
UPDATE 2:
i can’t CAST to Int32 because i receive this call from a EXE file:
MyProjectPrompt.exe Namespace.Class.Method param1 param2
Example:
MyProjectPrompt.exe It.Company.Math.Add 10 10
SOLUTION
ParameterInfo[] listaParametr = method_to_invoke.GetParameters();
ParameterInfo infoParam;
for(Int32 va=0;va<listaParametr.Length;va++)
{
infoParam = listaParametr[va];
for(Int32 va2=0;va2<args_values.Length;va2++)
{
if(args_names[va2]==infoParam.Name)
{
args_values[va2] = Convert.ChangeType(args_values[va2],
infoParam.ParameterType);
}
}
}
Basically for EVERY Param to pass, i cast it.
After that i pass it dynamically:
Object result_object = target_class.InvokeMember(method,
BindingFlags.InvokeMethod, null, target_object,
args_values, null, null, args_names);
Use
Convert.ChangeTypeto change your original value to a type accepted by the method. It’ll throw an exception if no suitable conversion can be found.