【发布时间】:2021-11-30 12:30:25
【问题描述】:
我是 C# 新手。我了解到派生类只能有一个基类。在我看来,这是 C# 的一个弱点,但也许我没有做对。我正在寻找“最好的”解决方案来解决这个问题,同时尊重 DRY 和干净的代码原则。 下面我创建了一个示例,我最终从两个类中派生出这个想法。有两个明显的解决方案:
- 在
CColoredRectangle和CColoredTriangle中实现CColor的成员和方法两次。但这违反了 DRY 原则 - 将
CColor的成员和方法实现到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# inheritance multiple-inheritance