可以说我有以下课程
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)
现在问题是最后一行无效.有没有一些优雅的方式来做到这一点?
Kir*_*oll 65
我不知道优雅,但做到这一点的方法是:
typeof(Creator)
.GetMethod("CreateAnimals")
.MakeGenericMethod(type)
.Invoke(creator, new object[] { 5 });
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 29
并不是的.基本上你需要使用反射.泛型实际上是针对静态类型而不是仅在执行时已知的类型.
要使用反射,您将使用Type.GetMethod获取方法定义,然后调用MethodInfo.MakeGenericMethod(type),然后像任何其他方法一样调用它.
尝试这个:
public List<T> CreateAnimals<T>(int numAnimals) where T : Animal
{
Type type = typeof(T);
List<T> returnList = new List<T>();
//Use reflection to populate list and return
}
Run Code Online (Sandbox Code Playgroud)
它应该确保 CreateAnimals 允许的类型继承自 Animal。那么希望不会有问题List<animalType> animals = creator.CreateAnimals<type>(5);