我有一個非常簡單的問題,但我之前沒有遇到過這個問題。接口引用另一個接口,但引用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; }
}
}
這是要走的路,或者是一個更好的辦法?
'Bar'是一個'IBar',但'IBar'不是'Bar'。 – 2013-05-03 10:57:15
這就是所謂的返回類型協方差,並根據[此篇](http://stackoverflow.com/questions/5709034/does-c-sharp-support-return-type-covariance)C#和CLR不支持它。 – Dirk 2013-05-03 10:59:05
「醜陋的解決方法」(也稱爲顯式接口實現)確實是C#中解決此問題的唯一方法。事實上,這是該功能首先存在的原因之一。 – dasblinkenlight 2013-05-03 11:00:23