【发布时间】:2021-01-05 02:41:07
【问题描述】:
我有一个关于打字和 contra/covairance 的问题。
给定以下类
public class BoardItemsHolderRepository<THolder, TBoardItem> : DataRepository<IList<THolder>>
where TBoardItem : BoardItem
where THolder : IBoardItemHolder<TBoardItem>
{
}
public interface IDataRepository<T> : IDataGetRepository<T>, IDataSetRepository<T> where T : class
{
}
public interface IDataGetRepository<out T> where T : class
{
IObservable<T> GetObservableStream();
IObservable<T> GetMostRecent();
}
public interface IDataSetRepository<in T> where T : class
{
void Set(T value);
}
public abstract class DataRepository<T> : IDataRepository<T> where T : class
{
..implementation details
}
public class ConstructHolder : IBoardItemHolder<Construct>
{
..implementation details
}
鉴于以上 3 个文件,有人可以向我解释为什么会发生以下情况吗?:
IDataGetRepository<IList<IBoardItemHolder<Construct>>> wontCompile = new BoardItemsHolderRepository<ConstructHolder, Construct>(); //illegal
IDataGetRepository<IList<ConstructHolder>> compile = new BoardItemsHolderRepository<ConstructHolder, Construct>(); //legal
我不明白为什么第一行的隐式转换不起作用,因为下面的行编译(如预期)
IBoardItemHolder<Construct>> compile = new ConstructHolder();
【问题讨论】:
标签: c# generics covariance contravariance strong-typing