簡體   English   中英

在 C# 中是否有可能與另一個接口的字段具有接口,但在實現中使用實現接口的 class?

[英]Is it possible in C# to have interface with fields of another interface but in the implementation use a class that implements an interface?

下面是一個示例實現。

但是當我這樣做時,我得到以下錯誤'Foo'沒有實現接口成員'IBar.MyBar'。

public interface IBar
{
    public int Id { get; set; }
}

public class Bar : IBar
{
    public int Id { get; set; }
}

public interface IFoo
{
    public IBar MyBar { get; }
}

public class Foo : IFoo
{
    public Bar MyBar { get; }
}

好吧,錯誤很明顯:接口IFoo指示一個名為MyBar的成員,類型為IBar ,而不是Bar 該合同確保您始終了解您可以從 API 獲得什么。 因此,以下內容總是會返回某種IBar

IFoo foo = GetMyFoo();
IBar bar = foo.MyBar; 

你的Bar類的實現是一個內部細節,客戶不應該關心。 因此,您可以輕松地交換該實現,而無需客戶端重新編譯。

不過,有一個建議 C#9使返回類型協變。

所以,復制代碼后,我認為你需要更改 Foo class 實現。

至於現在你有這個:

public class Foo : IFoo
{
    public Bar MyBar { get; }
}

而且我認為您的意思是這樣說,這將按您的意圖工作:

public class Foo : IFoo
{
   public IBar MyBar { get; }
}

請注意,在 IFoo 接口中,您將 MyBar 實現為 IBar 而不是 Bar,因此會出現錯誤。 如果我遺漏了什么,我很抱歉,但我認為這就是問題所在。 很高興我能幫助你::)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM