假设您有一个类层次结构:
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/