c# - 如何修改所有派生类中的方法返回值?

标签 c# .net oop design-patterns

假设您有一个类层次结构:

class Base
{
    public virtual string GetName()
    {
        return "BaseName";
    }
}

class Derived1 : Base
{
    public override string GetName()
    {
        return "Derived1";
    }
}

class Derived2 : Base
{
    public override string GetName()
    {
        return "Derived2";
    }
}

如何以最合适的方式编写代码,使所有“GetName”方法都将“XX”字符串添加到派生类的返回值中?

例如:

         Derived1.GetName returns "Derived1XX"

         Derived2.GetName returns "Derived2XX"

更改GetName 方法实现的代码不是一个好主意,因为可能存在多个Base 的派生类型。

最佳答案

保留 GetName 非虚拟,并将“追加 XX”逻辑放在该函数中。将名称(不带“XX”)提取到 protected 虚函数,并在子类中覆盖它。

class Base
{
    public string GetName()
    {
        return GetNameInternal() + "XX";
    }

    protected virtual string GetNameInternal() 
    {
        return "BaseName";
    }
}

class Derived1 : Base
{
    protected override string GetNameInternal()
    {
        return "Derived1";
    }
}

class Derived2 : Base
{
    protected override string GetNameInternal()
    {
        return "Derived2";
    }
}

关于c# - 如何修改所有派生类中的方法返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26130015/

相关文章:

c# - 将 ComboBox 下拉列表自动调整为 Silverlight 中的内容

c# - 如何在 C# 6 中使用带字符串插值的转义字符?

java - 面向对象结构设计

javascript - 为什么开发人员在 JavaScript 中使用 get 和 set 时使用 "_"?

c# - 如何在日历中保留所有日期选择?

c# - PKCS11证书

c# - 如何获取cassandra中键空间的所有表的列表

c# - 如何在 Visual Studio 2008 IDE 中订阅页面事件

.Net 4.0 Redistributable - 我在哪里可以找到它?

c++ - 如何检测是否将除整数以外的任何内容传递给我的类构造函数?