【发布时间】:2021-06-08 14:24:54
【问题描述】:
目标
构造一个实现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> { }) 修复了错误,但同时能够将任何类型的杂货放入冷藏袋中。这显然不应该发生:)
【问题讨论】:
标签: c# interface implicit-conversion derived-class