簡體   English   中英

派生接口之間沒有隱式引用轉換

[英]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> { } ) 修復了錯誤,但同時能夠將任何類型的雜貨放入冷藏袋中。 這顯然不應該發生:)

您的編譯錯誤是因為TIBag<T>中是不變的。

ICoolBagIBag<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.

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