首页 > 解决方案 > 如何避免 C# 中的“派生类只能有一个基类”问题?

问题描述

我是 C# 新手。我了解到派生类只能有一个基类。在我看来,这是 C# 的一个弱点,但也许我没有做对。我正在寻找“最好的”解决方案来解决这个问题,同时尊重 DRY 和干净的代码原则。下面我创建了一个示例,我最终从两个类中派生出这个想法。有两个明显的解决方案:

  1. 实现CColor 两次intoCColoredRectangle和的成员和方法CColoredTriangle。但这违反了 DRY 原则
  2. 实现CColorinto的成员和方法CShape(或派生一个CColoredShape类作为其他类的基础)。但是这些CColor方法在它们不应该存在的地方CRectangle可用。CTriangle这打破了干净代码的想法。

接口不会完成这项工作,因为它们不允许成员。有什么优雅的解决方案吗?提前致谢。

public abstract class CShape
{
    private double x,y;
    protected CShape(double x, double y)
    {
        this.x = x;
        this.y = y;
    }
    public abstract double Area { get; }


    public class CRectangle : CShape
    {
        protected CRectangle(double x, double y) : base(x, y) { }
        public override double Area => x * y;
    }
    public class CTriangle : CShape
    {
        protected CTriangle(double x, double y) : base(x, y) { }
        public override double Area => x * y * 0.5;
    }
    public class CColor
    {
        public int R,G,B; //I need members here, so an interface won't work
        public void MixColorWith(int r,int g,int b) { /*Code....*/}
    }
    public class CColoredTriangle : CTriangle, CColor //compiler error CS1721
    {

    }
    public class CColoredRectangle : CTriangle, CColor //compiler error CS1721
    {

    }
}

标签: c#inheritancemultiple-inheritance

解决方案


我了解到派生类只能有一个基类。在我看来,这是 C# 的一个弱点 [...]

让我们回顾一下您认为哪些事情是正确的,以便能够量化您认为这是 C# 的弱点的陈述。

您假设彩色三角形是一种颜色。这就是继承的意思,它是一种“is-a”关系。虽然存在一些不是彩色三角形的颜色,但您认为至少有一些颜色是彩色三角形。我们在同一页面上吗?

所以这是的观点:不存在一种颜色是彩色三角形。这里根本没有“is-a”关系。您也许可以证明彩色三角形“具有”颜色的事实,在这种情况下,您可以为其添加一个Color属性,但仅此而已。

所以你去了,你的问题不需要菱形(多重)继承。

编辑:你提出的另一件事,“我需要这里的成员,所以界面不起作用”,在这两个帐户上都是完全错误的。在 C# 中,接口可以同时具有属性和方法。


推荐阅读