invoke non static method in c# -
i want invoke class "***" solution works me want invoke solution gives me error :
type t = type.gettype(svclass); methodinfo method = t.getmethod("execute", bindingflags.instance| bindingflags.public); ret = (string)method.invoke(null, new object[] { context.request}); public string execute(httprequest req)
so tried methodinfo method = t.getmethod("execute", bindingflags.instance | bindingflags.public);
but gives me error "non-static method requires target"
*** working solution static method
type t = type.gettype(svclass); methodinfo method = t.getmethod("execute", bindingflags.static| bindingflags.public); ret = (string)method.invoke(null, new object[] { context.request});
to invoke
public class xxxxx { public static string execute(httprequest req){} }
the secret change binding flags methodinfo matches signature of method wish call.
eg:
public static string execute(httprequest req){}
will accessed via
methodinfo method = t.getmethod("execute", bindingflags.static| bindingflags.public);
however, access
public string execute(httprequest req){}
you need
var classobj = new class(); methodinfo method = classobj.gettype().getmethod("execute", bindingflags.instance| bindingflags.public);
instance means method member of class object, , not of class type. (instance vs static)
var parameterarray = new object[]{ yourhttprequesthere}; var result = method.invoke(classobj,parameterarray);
so remember, if method belongs instance, need grab method instance type, , need invoke reference instance variable (classobj) above.
Comments
Post a Comment