Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 变量和开放泛型IReadOnlyList_C#_Generics - Fatal编程技术网

C# 变量和开放泛型IReadOnlyList

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

我试图理解为什么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
}
类矩阵,其中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问题;)