How to invoke Dynamically a method of an instantied object in c# -
i want create method invokes public method, of instantied class, dynamically (using reflect).
first, have class:
namespace nfse.classes.models.classes.nfseweb { public class service { public string idservice { get; set; } public string name {get; set; } public getkey() { return idservice + name; } } } the method "getkey" in few classes.
ok till there... creating function returns value function getkey of object dynamically instantied.
i have function pass object parameter:
internal static string getvalordaclasse(object valor) { if (valor.tostring().contains("nfse.classes.models.classes")) { type mytype = type.gettype(valor.tostring()); object myobj = activator.createinstance(mytype); //invoking non-static method (how invoke non static method??) return (string)mytype.invokemember("getkey", bindingflags.invokemethod, null, myobj, new object[] { valor }); } else return valor.tostring(); } when try (get value method "getkey"... receive following exception: method 'nfse.classes.models.classes.nfseweb.service.getkey' not found.
all best!
you calling invokemember incorrectly. notice last parameter of invokemember, not passing getkey, null appropriate there. also, binding flags werent allowing proper method.
return (string)mytype.invokemember("getkey", bindingflags.invokemethod| bindingflags.public | bindingflags.declaredonly | bindingflags.instance, null, myobj, null); your service method:
namespace nfse.classes.models.classes.nfseweb { public class service { public string idservice { get; set; } public string name { get; set; } public string getkey() { return idservice + name; } } } your calling method:
static void main(string[] args) { var mystring = getvalordaclasse("nfse.classes.models.classes.nfseweb.service"); } public static string getvalordaclasse(object valor) { if (valor.tostring().contains("nfse.classes.models.classes")) { type mytype = type.gettype(valor.tostring()); object myobj = activator.createinstance(mytype); //invoking non-static method (how invoke non static method??) return (string)mytype.invokemember("getkey", bindingflags.invokemethod|bindingflags.public | bindingflags.declaredonly | bindingflags.instance, null, myobj, null); } else return valor.tostring(); }
Comments
Post a Comment