.net不允許在基類中實現部分接口。作爲一種緩解措施,我已經選擇了3種備選解決方案。請幫助我確定哪一個更適用於重構,編譯/運行時錯誤,可讀性。 但首先有幾條評論。C#在基類/抽象類中的最佳部分接口實現
- 當然,您可能總是將對象投射到IFoo並在沒有任何編譯器警告的情況下調用任何方法。但這不合邏輯,你不會那樣做。這個構造不會因重構而發生。
- 我想要最大的分離度。直接類合同(公共方法和屬性)應該與接口實現分開。我使用很多接口來分離對象的交互。
我比較:
- BaseClass1/MyClass1的:
- CON:有在BaseClass1創建虛擬抽象的IFoo的每個未實現的方法。
- con:其他方法包裝 - 運行時對生產力的影響很小。
- BaseClass2/MyClass2:
- CON:沒有編譯器警告,如果在MyClass2沒有實現方法2的。運行時異常。用單元測試覆蓋較差的重構可能會破壞代碼的穩定性。
- con:必須放置額外的過時構造來防止子類中的直接方法調用。
- con:Method2對於BaseClass1是公開的,所以它現在是類合同的一部分。必須放置「過時」構造以防止直接呼叫,而不是通過IFoo。
- BaseClass3/MyClass3:
- 親:(相較於#2)。更可讀。你會發現MyClass2.Method2是IFoo的實現,而不僅僅是一些重載方法。
public interface IFoo
{
void Method1();
void Method2();
}
public abstract class BaseClass1 : IFoo
{
void IFoo.Method1()
{
//some implementation
}
void IFoo.Method2()
{
IFooMethod2();
}
protected abstract void IFooMethod2();
}
public class MyClass1 : BaseClass1
{
[Obsolete("Prohibited direct call from child classes. only inteface implementation")]
protected override void IFooMethod2()
{
//some implementation
}
}
public abstract class BaseClass2 : IFoo
{
void IFoo.Method1()
{
//some implementation
}
[Obsolete("Prohibited direct call from child classes. only inteface implementation")]
public virtual void Method2()
{
throw new NotSupportedException();
}
}
public abstract class MyClass2 : BaseClass2
{
public override void Method2()
{
//some implementation
}
}
public abstract class BaseClass3 : IFoo
{
void IFoo.Method1()
{
//some implementation
}
void IFoo.Method2()
{
throw new NotSupportedException();
}
}
public abstract class MyClass3 : BaseClass3, IFoo
{
void IFoo.Method2()
{
//some implementation
}
}
這是一個**非常尷尬的模式,你試圖實現。你說*「.NET不允許在基類中實現部分接口。」* - 這是有原因的。客戶端代碼需要某種**實現接口**,或許...... **實現接口**。對於不支持的方法拋出異常,當然是*非常*糟糕的代碼異味... – Yuck 2012-02-07 12:47:47
同意Yuck。如果你有一個'IFoo'類型的變量,你真的希望'IFoo'的所有方法都可以實現並且可用。接口是爲了這個。 – ken2k 2012-02-07 12:51:32
只有MyClass1 _必須完全實現接口。它確實如此。問題是有多個子類(我沒有提及它),每個都必須實現IFoo。如果沒有基類,您必須複製/粘貼Method1實現,這對所有子類都是相同的。這是我想要避免的。但是Method2實現在子類中是不同的,所以我不能只有一個實現Method1和Method2的類。 – user1194528 2012-02-07 13:11:56