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

C# 如何修改所有派生类中的方法返回值?,c#,.net,oop,design-patterns,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

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

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方法实现的代码不是一个好主意,因为可能存在多种派生类型的基函数。

重写可以调用它的基函数。。。然后,您可以修改基类以将需要的字符追加到其中。

如果您不想(或不能)修改原始类,可以使用扩展方法:

static class Exts {
    public static string GetNameXX (this Base @this) {
        return @this.GetName() + "XX";
    }
}
您将能够像往常一样访问新方法:

new Derived1().GetNameXX();

GetName
保留为非虚拟,并将“append XX”逻辑放入该函数中。将名称(不带“XX”)提取到受保护的虚拟函数,并在子类中重写该名称

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";
    }
}

这是装饰器模式的一个很好的用例。创建一个具有对基的引用的装饰器:

class BaseDecorator : Base
{
    Base _baseType;

    public BaseDecorator(Base baseType)
    {
        _baseType = baseType;
    {

    public override string GetName()
    {
        return _baseType.GetName() + "XX";
    }
}

用您选择的类(基类或派生类)构造BaseDecorator,并在此基础上调用GetName。

您可以将名称的构造拆分为各种可重写部分,然后重写每个不同子类中的每个部分。 下面就是这样一个例子

public class Base {
  public string GetName() {
    return GetPrefix() + GetSuffix();
  }
  protected virtual string GetPrefix() {
    return "Base";
  }
  protected virtual string GetSuffix() {
    return "";
  }
}

public class DerivedConstantSuffix : Base {
  protected override string GetSuffix() {
    return "XX";
  }
}

public class Derived1 : DerivedConstantSuffix {
  protected override string GetPrefix() {
    return "Derived1";
  }
}

public class Derived2 : DerivedConstantSuffix {
  protected override string GetPrefix() {
    return "Derived2";
  }
}

这通常不是一个好的设计。如果您不想在子对象中更改某些内容,请将其设置为
密封的
。@Renan方法在默认情况下是密封的,它们必须是
虚拟的
,才能重写。如果类是密封的,则不能有子类。OP确实希望
GetName
在每个孩子身上返回不同的东西-他只需要一个通用后缀。@Blorgbeard true.dat。我已经完全忘记了。@Renan实际上我只是说,当你重写方法时,你实际上可以密封它们,这样它们就不能再被重写了。但它只允许在虚拟方法的重写上使用。这似乎是一个很好的解决方案。另一个可以应用的模式是