可以说我有以下课程
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)
现在问题是最后一行无效.有没有一些优雅的方式来做到这一点?