假设我有以下类:
现在,在一些稍后的代码中,我想读取要创建的动物是什么。
现在的问题是最后一行不合法。有没有更优雅的方法来解决这个问题呢?
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
}
}
现在,在一些稍后的代码中,我想读取要创建的动物是什么。
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);
现在的问题是最后一行不合法。有没有更优雅的方法来解决这个问题呢?