c# - How to invoke static generic class methods if the generic type parameters are unknown until runtime? -
assume have static generic class. generic type parameters not available until runtime. how invoke members?
please see following code snippet:
static class utility<t> { public static void dosomething() { } } class tester { static type gettypeatruntime() { // return object of type type @ runtime. } static void main(string[] args) { type t = gettypeatruntime(); // want invoke utility<>.dosomething() here. how this? } }
edit:
ok, solution based on responses given 2 guys below. both of you!
static class utility<t> { //trivial method public static void dosomething(t t) { console.writeline(t.gettype()); } } // assume foo unknown @ compile time. class foo { } class tester { static void main(string[] args) { type t = typeof(foo);// assume foo unknown @ compile time. type gentype = typeof(utility<>); type con = gentype.makegenerictype(new type[] { t }); methodinfo mi = con.getmethod("dosomething", bindingflags.static | bindingflags.public); mi.invoke(null, new object[] { activator.createinstance(t) }); } }
then you'll need use reflection method , invoke it. generic type arguments needs resolved compile time if going declare object of type:
type t= gettypeatruntime();; var dosomething = typeof(list<>).makegenerictype(t).getmethod("dosomething", bindingflags.static | bindingflags.public); dosomething.invoke(null, new object[] { });
however in example t not used in method signature or implementation , if that's case i'd move non-generic base class.
disclaimer: suggested solution meant can if want example seems mpore issue of design. i'd suggest revisiting use of static/generic in case
Comments
Post a Comment