我试图理解为什么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
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么这不起作用:
_lines属于类型TLine[],实现IReadOnlyList<TLine>IReadOnlyList<out T>是一个变体通用接口,据我所知,这意味着任何实现IReadOnlyList<TLine>都可以用作IReadOnlyList<ILine>我觉得必须是因为不考虑类型约束,但我对此表示怀疑.
Jon*_*eet 13
您只需要将class约束添加到TLine:
class Matrix<TLine> where TLine : class, ILine
Run Code Online (Sandbox Code Playgroud)
这将确保它TLine是一种引用类型 - 然后允许通用方差起作用.方差仅适用于引用类型,因为CLR知道类型的值TLine可以用作类型的值,ILine而不会在表示中进行任何装箱或其他更改.