c# - How do I translate from typeName strings to generics? -
the context of question mvc app takes strings , converts them types , hands them off generic code.
- i have string representation of type input.
- i can't seem ever put
typevariable inside<>generic method. - does mean have manually spell out possible cases , generic method calls? right way this?
- it cool if
modelbinderfigure out type somehow have generic type parameter action methodpublic actionresult something<t>(). don't know if possible.
example
public actionresult dosomething(string typename, int? id) { var type = type.gettype(typename); if (type == typeof(apple)) dosomethingelse<apple>(id); if (type == typeof(orange)) dosomethingelse<orange>(id); //if etc ... infinity }
if have type you'd have via reflection. assuming "dosomethingelse" method in current class:
public actionresult dosomething(string typename, int? id) { type thistype = this.gettype(); // current class type var type = type.gettype(typename); methodinfo dosomethingelseinfo = thistype.getmethod("dosomethingelse"); methodinfo concretedosomethingelse = dosomethingelseinfo.makegenericmethod(type); concretedosomething.invoke(this, null); } that should work you, although should note, it's not going pretty! ;)
Comments
Post a Comment