尝试使用泛型:
public static BaseClass Create() where T : BaseClass, new() { T newVar = new T(); // Do something with newVar return T; }
样品用途:
DerivedClass d = BaseClass.Create();
有两个主要选择.更好更新的是使用泛型,另一种是使用反射.我提供这两个以防你需要开发一个在.NET 2.0之前工作的解决方案.
abstract class BaseClass { public static BaseClass Create() where T : BaseClass, new() { return new T(); } }
用法如下:
DerivedClass derivedInstance = BaseClass.Create();
abstract class BaseClass { public static BaseClass Create(Type derivedType) { // Cast will throw at runtime if the created class // doesn't derive from BaseClass. return (BaseClass)Activator.CreateInstance(derivedType); } }
使用的位置(为了便于阅读,分为两行):
DerivedClass derivedClass = (DerivedClass)BaseClass.Create(typeof(DerivedClass));