C# 变量和开放泛型IReadOnlyList
我试图理解为什么c#中关于变量和泛型的特定行为无法编译C# 变量和开放泛型IReadOnlyList,c#,generics,C#,Generics,我试图理解为什么c#中关于变量和泛型的特定行为无法编译 class Matrix<TLine> where TLine : ILine { TLine[] _lines; IReadOnlyList<ILine> Lines { get { return _lines; } } //does not compile IReadOnlyList<TLine> Lines { get { return _lines; } } //comp
class Matrix<TLine> where TLine : ILine
{
TLine[] _lines;
IReadOnlyList<ILine> Lines { get { return _lines; } } //does not compile
IReadOnlyList<TLine> Lines { get { return _lines; } } //compile
}
类矩阵,其中TLine:ILine
{
t线[]_线;
IReadOnlyList行{get{return\u Lines;}}}//未编译
IReadOnlyList行{get{return\u Lines;}}//compile
}
我不明白为什么这不起作用:
属于\u行
类型,实现了TLine[]
IReadOnlyList
是一个变体通用接口,据我所知,这意味着实现IReadOnlyList
的任何东西都可以用作IReadOnlyList
IReadOnlyList
我觉得这一定是因为没有考虑类型约束,但我对此表示怀疑。您只需要将
类
约束添加到TLine
:
class Matrix<TLine> where TLine : class, ILine
类矩阵,其中TLine:class,ILine
这将确保
TLine
是一种参考类型,从而允许通用差异发挥作用。方差仅适用于引用类型,因为这样CLR知道类型TLine
的值可以用作类型ILine
的值,而不需要任何装箱或其他表示形式的更改。我认为您需要向TLine
-类矩阵添加class
约束,其中TLine:ILine,类
。如果T
是一个值类型,则IReadOnlyList
的协方差不适用,因此您需要将TLine
限制为引用类型。@Lee我也不知道,您应该将其作为答案发布,因为它解决了OPs问题;)