2013-02-28 69 views
1

的例子是這樣的:如何實現一個已經有一些其他接口的接口?

interface IA 
{ 
    ICollection<IB> Bs {get;set;} 
} 

interface IB 
{ 
} 


public class BBase : IB 
{ 

} 

public class ABase : IA 
{ 
    public ICollection<BBase> Bs { get; set; } 
} 

的問題是,當我想實現的接口IABBase,就像我在ABase一樣,發生錯誤。是說我只能用IB而不是BBase來執行IAABase

回答

7

你需要做的是讓IA通用:

interface IA<T> where T : IB 
{ 
    ICollection<T> Bs { get; set; } 
} 

interface IB 
{ 
} 


public class BBase : IB 
{ 

} 

public class ABase : IA<BBase> 
{ 
    public ICollection<BBase> Bs { get; set; } 
} 

接口的實現究竟應在其定義相匹配,所以在非通用情況下,你預計將有恰好ABaseICollection<IB> Bs {get;set;},即它可以接受任何IB實施。

雖然接口是通用的(interface IA<T> where T : IB),但是它的實現應該提供滿足給定約束(即,這裏的一些確切的實現IB)的任何T。因此ABase類也變得通用。

欲瞭解更多信息閱讀:

  1. Generic Interfaces (C# Programming Guide)
  2. where (generic type constraint) (C# Reference)
+0

+1 - 可接受的有用方法。將接口簽名更改爲通用可能無法在所有情況下使用。 – 2013-02-28 07:28:10

+0

@AlexeiLevenkov同意..在這種情況下,在我看來,OP只是開始設計 – horgh 2013-02-28 07:33:11

+0

非常感謝! – user2118486 2013-02-28 07:42:48

2

您不能爲它指定不同類型的執行財產 - 見Interfaces (C# Programming Guide)

爲了實現一個接口成員,這個工具的相應成員nting類必須是公開的,非靜態的,並且具有相同的名稱和簽名的接口成員

在您的特定情況下,您可能需要使用ICollection<IB>作爲一種財產在ABase或跟隨康斯坦丁Vasilcov建議,使用通用IA<T>

如果你不能去通用路線考慮在界面'獲得' - 只做屬性。這樣,您將無法在課程中提供setter,並通過使用自定義方法將項目添加到集合來驗證所有「添加到集合」操作。

相關問題