c# - 如何避免 C# 中的“派生类只能有一个基类”问题?
问题描述
我是 C# 新手。我了解到派生类只能有一个基类。在我看来,这是 C# 的一个弱点,但也许我没有做对。我正在寻找“最好的”解决方案来解决这个问题,同时尊重 DRY 和干净的代码原则。下面我创建了一个示例,我最终从两个类中派生出这个想法。有两个明显的解决方案:
- 实现
CColor
两次intoCColoredRectangle
和的成员和方法CColoredTriangle
。但这违反了 DRY 原则 - 实现
CColor
into的成员和方法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# 的一个弱点 [...]
让我们回顾一下您认为哪些事情是正确的,以便能够量化您认为这是 C# 的弱点的陈述。
您假设彩色三角形是一种颜色。这就是继承的意思,它是一种“is-a”关系。虽然存在一些不是彩色三角形的颜色,但您认为至少有一些颜色是彩色三角形。我们在同一页面上吗?
所以这是我的观点:不存在一种颜色是彩色三角形。这里根本没有“is-a”关系。您也许可以证明彩色三角形“具有”颜色的事实,在这种情况下,您可以为其添加一个Color
属性,但仅此而已。
所以你去了,你的问题不需要菱形(多重)继承。
编辑:你提出的另一件事,“我需要这里的成员,所以界面不起作用”,在这两个帐户上都是完全错误的。在 C# 中,接口可以同时具有属性和方法。
推荐阅读
- python - Request.Session 不保存 cookie
- random - xoshiro / xoroshiro 和零
- sql - 如何选择与某个小时最近的时间对应的数据?
- php - 如何编辑“尾巴”的输出?
- adfs - 如何根据 AD 组发出声明(布尔值)
- c# - 识别 DateTime 间隔接近度,并考虑以前的间隔
- javascript - 对于来自 Vue.js 和 Vuetify.js 中的函数的表中的数据
- java - 如果我在 Kotlin 中编程,为什么这是一个 Java 文件
- php - 尝试保存到数据库时出错调用未定义的方法 stdClass::save()
- android - 如何将 alpah 设置为
在xml中?