【问题标题】:Is it possible to construct a derived class in the abstract base class? [closed]是否可以在抽象基类中构造派生类? [关闭]
【发布时间】:2020-06-07 14:11:31
【问题描述】:

假设您有以下三个类(我省略了实现):

abstract class BaseClass
class Derived1 : BaseClass
class Derived2 : BaseClass

现在,在BaseClass 中,我想定义一个方法,该方法应该返回相同实例的新的、稍加修改的版本。但问题是:我无法构造 BaseClass,因为它是抽象的,而且我不知道您使用的是哪个派生类,因为我们在 BaseClass 中。

我能想到的唯一解决方法是让它成为一个抽象方法,并让每个派生类实现它自己的版本。但这将是大量重复的代码,只更改了一个类名。有没有更好的方法来做到这一点?

【问题讨论】:

  • 仅供参考,如果您从抽象 BaseClass 中调用 .GetType(),则返回的类型将是 Derived 类。所以BaseClass 应该知道你使用的是哪个派生类。
  • new Derived2() 有什么问题; ?

标签: c# inheritance abstract-class


【解决方案1】:

使用泛型类型怎么样?

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>();

【讨论】:

    猜你喜欢
    • 2012-05-21
    • 2010-09-21
    • 2013-08-21
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 2017-05-25
    相关资源
    最近更新 更多