c# - specifying a generic type parameter using a string -
suppose have method
public void whatever<t>() { ... }
suppose have type in form of string
var mytype = "system.string";
normally, i'd call method like:
whatever<string>();
but i'd able call using mytype somehow. possible? know doesn't work, conceptually:
whatever<type.gettype(mytype)>();
you can use reflection , methodinfo.makegenericmethod this
reflect method want call methodinfo
, make generic , invoke it.
something (notice top of head (no vs here), might not perfect yet should started):
type type = myobject.gettype(); methodinfo method = type.getmethod("nameofmethod"); methodinfo genericmethod = method.makegenericmethod(typeof(string)); genericmethod.invoke(myobject, new object[] { "thestring" } );
Comments
Post a Comment