[英]No implicit reference conversion between derived interfaces
構造一個具體的 object 實現ICoolbag
並且只能存儲ICoolBagGrocery
而不是任何類型的雜貨IGrocery
。
下面的實現會導致以下錯誤:
The type 'SolidDistribution.Core.Bag.CoolBag.ICoolBag' cannot be used as type parameter 'T'
in the generic type or method 'IBagStorage<T>'. There is no implicit reference conversion from
'SolidDistribution.Core.Bag.CoolBag.ICoolBag' to 'SolidDistribution.Core.Bag.IBag<SolidDistribution.Core.IGrocery>'.
包
// A bag that can only hold coolbag groceries.
public interface ICoolBag : IBag<ICoolBagGrocery> { }
// a bag that can hold any type of grocery.
public interface IBag<T> : IGroceryStorage<T> where T : IGrocery { }
貯存
// A storage that can store any type of grocery.
public interface IGroceryStorage<T> : IStorage<T> where T : IGrocery { }
// A storage that can store any type of bag.
public interface IBagStorage<T> : IStorage<T> where T : IBag<IGrocery> { }
// Base storage interface.
public interface IStorage<T> { }
雜貨店
// A grocery that can only be stored in a coolbag.
public interface ICoolBagGrocery : IGrocery { }
// Base grocery interface.
public interface IGrocery { }
盒子
// A box with a bag that can only hold coolbag groceries.
public interface ICoolBox : IBoxWithBag<ICoolBag> { }
// Base box with bag storage interface.
public interface IBoxWithBag<T> : IBox, IBagStorage<T> where T : IBag<IGrocery> { }
// Base box interface.
public interface IBox { }
將ICoolbag
更改為使用IGrocery
而不是ICoolBagGrocery
,如下所示:( public interface ICoolBag: IBag<IGrocery> { }
) 修復了錯誤,但同時能夠將任何類型的雜貨放入冷藏袋中。 這顯然不應該發生:)
您的編譯錯誤是因為T
在IBag<T>
中是不變的。
ICoolBag
是IBag<ICoolBagGrocery>
,但IBag<ICoolBagGrocery>
不是IBag<IGrocery>
。
如果您要在IBag<T>
中使T
協變(使用out
),那么IBag<ICoolBagGrocery>
將是IBag<IGrocery>
:
public interface IBag<out T> : IGroceryStorage<T> where T : IGrocery { }
但是,這會對您的IBag<T>
接口施加限制:類型T
的屬性不允許set
,並且方法只能使用T
作為返回類型,而不是參數類型。
例如:
public interface IBag<out T> : IGroceryStorage<T> where T : IGrocery
{
T SomeProperty { get; } // Allowed
T AnotherProperty { get; set; } // Compilation error
T SomeMethod(); // Allowed
void AnotherMethod(T t); // Compilation error
}
此外,方差將通過 inheritance 層次結構上升,這意味着T
還需要在IGroceryStorage<T>
和IStrorage<T>
中是協變的,以使其有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.