I am trying to write code that will infer types from a list of parameters, and then call a method that matches these parameters. This works very well, unless the parameter list is null in it.
I am wondering how I can call a Type.GetMethod call to match the function / overload, even with the null parameter in the parameter list.
object CallMethodReflection(object o, string nameMethod, params object[] args) { try { var types = TypesFromObjects(args); var theMethod = o.GetType().GetMethod(nameMethod, types); return (theMethod == null) ? null : theMethod.Invoke(o, args); } catch (Exception ex) { return null; } } Type[] TypesFromObjects(params object[] pParams) { var types = new List<Type>(); foreach (var param in pParams) { types.Add((param == null) ? null : param.GetType()); } return types.ToArray(); }
The main problem is types.Add((param == null) ? null : param.GetType()); , which will cause the GetMethod call to fail using the null value in the type array.
void Function1(string arg1){ } void Function1(string arg1, string arg2){ } void Function1(string arg1, string arg2, string arg3){ } void Function2(string arg1){ } void Function2(string arg1, int arg2){ } void Function2(string arg1, string arg2){ } CallMethodReflection(obj, "Function1", "String", "String");
Basically, I am trying to determine how to change my code so that the line /*2*/ works.
reflection null c #
palswim
source share