c# - Invoke Methods having Different Parameters -
i facing 1 issue in invoking different methods having different types of parameter. eg. have 3 methods a, b, c parameters follows.
a(string text, int num) b(bool type, int num2) c(string text2, boolean type2, int num3)
now how invoke these 3 methods 1 one? method names fetched string , stored in array, , after storing them, methods needs invoked using each loop.
you can keep in dictionary
method names , parameters string
, object[]
dictionary<string, object[]> methodsinfo = new dictionary<string, object[]> { { "a", new object[] { "qwe", 4 }}, { "b", new object[] { true, 5 }}, { "c", new object[] { "asd", false, 42 }} };
and invoke them using invoke
from methodinfo
foreach (keyvaluepair<string, object[]> methodinfo in methodsinfo) { gettype().getmethod(methodinfo.key).invoke(this, methodinfo.value); }
if methods in class invoke them this
type classtype = type.gettype("namespace.classname"); object classobject = classtype.getconstructor(type.emptytypes).invoke(new object[] { }); foreach (keyvaluepair<string, object[]> methodinfo in methodsinfo) { classtype.getmethod(methodinfo.key).invoke(classobject, methodinfo.value); }
note: getconstructor(type.emptytypes)
empty constructor, parameterized constructor (say int
) use getconstructor(new[] { typeof(int) }).invoke(new object[] { 3 }
Comments
Post a Comment