简体   繁体   English

变体和开放式泛型IReadOnlyList

[英]Variant and open generics IReadOnlyList

I'm trying to understand why a specific behavior regarding variant and generics in c# does not compile. 我试图理解为什么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
}

I can't understand why this does not work as : 我不明白为什么这不起作用:

  • _lines , being of type TLine[] , implements IReadOnlyList<TLine> _lines ,类型为TLine[] ,实现IReadOnlyList<TLine>
  • IReadOnlyList<out T> is a variant generic interface, which means, as far as I understand, that anything implementing IReadOnlyList<TLine> can be used as a IReadOnlyList<ILine> IReadOnlyList<out T>是一个变体泛型接口,据我所知,这意味着任何实现IReadOnlyList<TLine>东西都可以用作IReadOnlyList<ILine>

I feel that it must be because the type constraint is not taken into account, but I doubt it. 我觉得必须是因为不考虑类型约束,但我对此表示怀疑。

You just need to add the class constraint to TLine : 您只需要将class约束添加到TLine

class Matrix<TLine> where TLine : class, ILine

This will ensure that TLine is a reference type - which then allows generic variance to work. 这将确保TLine是一种引用类型 - 然后允许通用方差工作。 Variance only works for reference types, because that way the CLR knows that the value of type TLine can be used as a value of type ILine without any boxing or other change in representation. 方差适用于引用类型,因为CLR知道TLine类型的值可以用作ILine类型的值,而不需要任何装箱或其他表示更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM