C# Getting Type out of a string variable and using it in generic method

前端 未结 3 1330
灰色年华
灰色年华 2021-01-29 05:59

I want to be able to get the actual Type of a string value I receive by some means (i.e from database) so I can use that Type in generic method like DoSomething

3条回答
  •  不思量自难忘°
    2021-01-29 06:24

    You can use a dictionary which holds all your types with strings keys:

    var d = new Dictionary(); 
    d.Add("Car",typeof(Car)); 
    d.Add("Plane",typeof(Plane)); 
    

    Then if you get the string "Car" from the database you can get the type like this:

    var myType = d["Car"]; 
    

    Then use myType as the real Type.

提交回复
热议问题