我是 C# 的新手。我了解到派生類只能有一個基類。在我看來,這是 C# 的一個弱點,但也許我沒有做對。我正在尋找“最佳”解決方案來解決這個問題,同時尊重 DRY 和干凈的代碼原則。下面我創建了一個示例,其中我最終從兩個類派生來展示這個想法。對此有兩個明顯的解決方案:
- 執行委員和方法
CColor兩次進入CColoredRectangle和CColoredTriangle。但這違反了 DRY 原則 - 實作
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
{
}
}
uj5u.com熱心網友回復:
我了解到派生類只能有一個基類。在我看來,這是 C# 的一個弱點 [...]
讓我們回顧一下您認為哪些事情是正確的,以便能夠量化說明這是 C# 的弱點的說法,再次在您看來。
你假設一個彩色三角形是一個 color。這就是繼承的意思,它是一種“is-a”關系。雖然存在一些不是彩色三角形的顏色,但您假設至少有一些顏色是彩色三角形。我們在同一頁面上嗎?
所以這是我的觀點:不存在一種顏色是彩色三角形。這里根本沒有“is-a”關系。您可能能夠證明彩色三角形“具有”顏色這一事實,在這種情況下,您可以Color為其添加一個屬性,但僅此而已。
所以你去了,你的問題不需要鉆石(多重)繼承。
編輯:另外,你假設的另一件事,“我需要這里的成員,所以界面不起作用”,這在兩個帳戶上都是完全錯誤的。在 C# 中,介面可以同時具有屬性和方法。
uj5u.com熱心網友回復:
一般來說,大多數專家都說你應該“更喜歡組合而不是繼承”。
在這種情況下,這幾乎肯定是正確的做法。
ACColoredTriangle 不是 a CColor,它有 a CColor,因此它應該只是它的一個屬性。
鑒于您似乎也希望能夠僅通過物件有一個 來參考物件CColor,而不管它們是什么形狀,創建IHasColor介面是有意義的
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;
public void MixColorWith(int r,int g,int b) { /*Code....*/}
}
public interface IHasColor
{
CColor Color {get; set;}
}
public class CColoredTriangle : CTriangle, IHasColor
{
CColor Color {get; set;}
}
public class CColoredRectangle : CTriangle, IHasColor
{
CColor Color {get; set;}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314604.html
