【发布时间】:2017-01-06 10:40:40
【问题描述】:
我试图了解为什么 c# 中有关变体和泛型的特定行为无法编译。
class Matrix<TLine> where TLine : ILine
{
TLine[] _lines;
IReadOnlyList<ILine> Lines { get { return _lines; } } //does not compile
IReadOnlyList<TLine> Lines { get { return _lines; } } //compile
}
我不明白为什么这不起作用:
-
_lines,属于TLine[],实现IReadOnlyList<TLine> -
IReadOnlyList<out T>是一个变体通用接口,据我所知,这意味着任何实现IReadOnlyList<TLine>的东西都可以用作IReadOnlyList<ILine>
感觉一定是因为没有考虑类型约束,但我怀疑。
【问题讨论】:
-
我认为您需要在
TLine-class Matrix<TLine> where TLine : ILine, class中添加一个class约束。如果T是值类型,则IReadOnlyList<T>的协方差不适用,因此您需要将TLine限制为引用类型。 -
@Lee 我也不知道,您应该将其发布为答案,因为它解决了 OPs 问题;)