2013-05-03 61 views
2

我有一個非常簡單的問題,但我之前沒有遇到過這個問題。接口引用另一個接口,但引用C#中的另一個類的類

看看這個代碼:

interface IFoo 
{ 
    IBar MyBar { get; } 
} 

interface IBar 
{ 
    String Test { get; } 
} 

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

class Bar : IBar 
{ 
    public String Test { get; set; } 
} 

的問題是,富不實現IFoo的,因爲它返回酒吧,而不是伊巴爾。但是自從Bar執行IBar以來我沒有看到問題。我想念什麼?

我想我的應用程序使用的類Foo,但暴露的IFoo到解決方案的其他部分。

這是變通的辦法,但它似乎是一個醜陋的解決方案:

class Foo : IFoo 
{ 
    public Bar MyBar { get; set; } 
    IBar IFoo.MyBar { 
     get { return this.MyBar; } 
    } 
} 

這是要走的路,或者是一個更好的辦法?

+1

'Bar'是一個'IBar',但'IBar'不是'Bar'。 – 2013-05-03 10:57:15

+0

這就是所謂的返回類型協方差,並根據[此篇](http://stackoverflow.com/questions/5709034/does-c-sharp-support-return-type-covariance)C#和CLR不支持它。 – Dirk 2013-05-03 10:59:05

+3

「醜陋的解決方法」(也稱爲顯式接口實現)確實是C#中解決此問題的唯一方法。事實上,這是該功能首先存在的原因之一。 – dasblinkenlight 2013-05-03 11:00:23

回答

2

你可以這樣做:

interface IFoo<out B> where B:IBar 
{ 
    B MyBar { get; } 
} 

interface IBar 
{ 
    String Test { get; } 
} 

class Foo : IFoo<Bar> 
{ 
    public Bar MyBar { get; set; } 
} 

class Bar : IBar 
{ 
    public String Test { get; set; } 
} 

這隻會在案件的工作,B是在輸出位置(原因很明顯,如果你認爲它足夠長的時間)。

-1

問題是Foo沒有實現IFoo,因爲它返回的是Bar而不是IBar。但是自從Bar執行IBar以來我沒有看到問題。我想念什麼?

是的。你錯誤地解釋了IFoo接口的合約。該合同是簡單的:一個名爲MyBar

一個屬性,有一個getter和具有伊巴爾的返回類型。合同不是返回一個IBar類型的對象,而是返回類型是IBar類型。

這是標準。嘗試執行ICloneable接口,該接口具有單一方法Clone(),返回類型爲object。實現這個接口意味着你必須實現一個返回類型爲object的方法,無論如何。即使你想要更具體些,任何其他的返回類型都不具備資格。

圍繞它你所建議的方式是正確的方式去做一個 - 具有返回酒吧屬性的IBAR屬性。或者,你知道,你可以只是有IBAR屬性並將其設置爲一個酒吧實例,因爲這是完全有效的,然後通過伊巴爾合同的伊巴爾對象工作。這將有助於脫鉤。