【问题标题】:How to have a default method while still be able to override it? [duplicate]如何在仍然能够覆盖它的同时拥有默认方法? [复制]
【发布时间】:2014-10-26 13:45:15
【问题描述】:

这是一个 C# 项目。

我有几个从基类继承的类。大多数子类具有相同的行为,而其中一些行为不同。

我正在使用 new 关键字。

public class Parent
{
    public DataTable FetchScore()
    {
        // blahblah
    }
}

public class ChildNormal : Parent
{
}

public class ChildOdd : Parent
{
    public new DataTable FetchScore()
    {
        DataTable dt = base.FetchScore();
        // blahblah
    }
}

但构建表明使用new 不是一个好习惯。

我也不能使用virtualoverride,因为我想要一个默认值。我不想多次复制相同的覆盖实现。

如何在 C# 中做到这一点?

【问题讨论】:

  • 您可以使用virtual和override,只需将virtual基方法放在基类中即可。
  • 另请参阅 here 了解 为什么 使用 new (可能)不是您想要做的。

标签: c#


【解决方案1】:

您需要声明基础virtual(这意味着它可以在必要时被覆盖)和override 在您需要与原始行为不同的地方。未覆盖的派生类的行为与基类一样。

public class Parent()
{
    public virtual DataTable FetchScore()
    {
        // blahblah
    }
}

public class ChildNormal() : Parent
{
}

public class ChildOdd() : Parent
{
    public override DataTable FetchScore()
    {
        DataTable dt = base.FetchScore();
        // blahblah
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2019-09-26
    相关资源
    最近更新 更多