我試圖構建一個使用的C#泛型功能的工廠方法。C#泛型 - 約束的類型參數
在此工廠方法我想將其約束到一些特定的類,所有這些沒有一個默認的構造函數。
這裏是我的榜樣。有人能告訴我是否可以運行它嗎?
public class AbstractClass {
//this abstract class does not have a default constructor, nor its subclasses
public AbstractClass(SomeClassName obj) {
//use obj for initialization
}
}
//this factory class should create objects of type T that inherit
//from AbstractClass and invoke the non-default constructor
public class FactoryClass {
public static T BuildObject<T> (SomeClassName obj) where T: AbstractClass {
return new T(obj); //does not work?!?!?!
}
}
//Edit: ANSWER!!!
public static T BuildObject<T>(SomeClassUsedForTheConstructor item) where T : SomeAbstractClass {
return (T) Activator.CreateInstance(typeof (T), item);
}
這是我以前使用的,但現在我使用Brian提到的Activator.CreateInstance。 – 2009-09-16 18:59:53