一個通用的方法可以說我有以下類調用帶有動態類型
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);
現在問題是最後一行是無效的。那麼有沒有一些優雅的方式來做到這一點?
泛型不是真正的方式去這裏,你應該創建一個List而不是使用Activator來創建派生類。 –
Doggett
2010-11-04 22:24:49