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 type variable inside <> generic method.
  • does mean have manually spell out possible cases , generic method calls? right way this?
  • it cool if modelbinder figure out type somehow have generic type parameter action method public 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

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -