是否可以在抽象基class中构造派生class?
Is it possible to construct a derived class in the abstract base class?
假设您有以下三个 classes(我省略了实现):
abstract class BaseClass
class Derived1 : BaseClass
class Derived2 : BaseClass
现在,在 BaseClass
中,我想定义一个方法,该方法应该 return 同一实例的一个新的、稍作修改的版本。但这就是问题所在:我无法构造 BaseClass
因为它是抽象的,而且我不知道你使用的是哪个派生的 class 因为我们在 BaseClass
.
我能想到的唯一解决方法是使它成为一个抽象方法,并使每个派生的 class 实现它自己的版本。但是,仅更改一个 class 名称就需要大量重复代码。有没有更好的方法来做到这一点?
使用泛型类型怎么样?
public abstract class BaseClass
{
public T GetSlightlyModifiedInstance<T>() where T : new, BaseClass
{
return new T(); // Do whatever there
}
}
然后就可以这样使用了
Derived1 derived1 = new Derived1();
Derived2 derived2 = new Derived2();
Derived1 modifiedDerived1 = derived1.GetSlightlyModifiedInstance<Derived1>();
Derived2 modifiedDerived2 = derived2.GetSlightlyModifiedInstance<Derived2>();
假设您有以下三个 classes(我省略了实现):
abstract class BaseClass
class Derived1 : BaseClass
class Derived2 : BaseClass
现在,在 BaseClass
中,我想定义一个方法,该方法应该 return 同一实例的一个新的、稍作修改的版本。但这就是问题所在:我无法构造 BaseClass
因为它是抽象的,而且我不知道你使用的是哪个派生的 class 因为我们在 BaseClass
.
我能想到的唯一解决方法是使它成为一个抽象方法,并使每个派生的 class 实现它自己的版本。但是,仅更改一个 class 名称就需要大量重复代码。有没有更好的方法来做到这一点?
使用泛型类型怎么样?
public abstract class BaseClass
{
public T GetSlightlyModifiedInstance<T>() where T : new, BaseClass
{
return new T(); // Do whatever there
}
}
然后就可以这样使用了
Derived1 derived1 = new Derived1();
Derived2 derived2 = new Derived2();
Derived1 modifiedDerived1 = derived1.GetSlightlyModifiedInstance<Derived1>();
Derived2 modifiedDerived2 = derived2.GetSlightlyModifiedInstance<Derived2>();