当在编译时未知类型参数但是在运行时动态获取时,调用泛型方法的最佳方法是什么?
考虑以下示例代码 - 在Example()方法内部,GenericMethod<T>()使用Type存储在myType变量中调用的最简洁方法是什么?
public class Sample
{
public void Example(string typeName)
{
Type myType = FindType(typeName);
// What goes here to call GenericMethod<T>()?
GenericMethod<myType>(); // This doesn't work
// What changes to call StaticMethod<T>()?
Sample.StaticMethod<myType>(); // This also doesn't work
}
public void GenericMethod<T>()
{
// ...
}
public static void StaticMethod<T>()
{
//...
}
}
Run Code Online (Sandbox Code Playgroud) 可以说我有以下课程
public class Animal { .... }
public class Duck : Animal { ... }
public class Cow : Animal { ... }
public class Creator
{
public List<T> CreateAnimals<T>(int numAnimals)
{
Type type = typeof(T);
List<T> returnList = new List<T>();
//Use reflection to populate list and return
}
}
Run Code Online (Sandbox Code Playgroud)
现在在一些代码中,我想读一下要创建的动物.
Creator creator = new Creator();
string animalType = //read from a file what animal (duck, cow) to create
Type type = Type.GetType(animalType);
List<animalType> animals = creator.CreateAnimals<type>(5);
Run Code Online (Sandbox Code Playgroud)
现在问题是最后一行无效.有没有一些优雅的方式来做到这一点?
var custsType = Type.GetType("Customers");
var customers = Json.Deserialize<custsType>(data);
Run Code Online (Sandbox Code Playgroud)
这显然失败了。如何通过字符串名称引用该类,以便在运行时提供它?
另外,我需要能够访问实际的强类型对象,而不是它的字符串表示形式。