【问题标题】:Variant and open generics IReadOnlyList变体和开放泛型 IReadOnlyList
【发布时间】: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&lt;TLine&gt;
  • IReadOnlyList&lt;out T&gt; 是一个变体通用接口,据我所知,这意味着任何实现IReadOnlyList&lt;TLine&gt; 的东西都可以用作IReadOnlyList&lt;ILine&gt;

感觉一定是因为没有考虑类型约束,但我怀疑。

【问题讨论】:

  • 我认为您需要在TLine - class Matrix&lt;TLine&gt; where TLine : ILine, class 中添加一个class 约束。如果T 是值类型,则IReadOnlyList&lt;T&gt; 的协方差不适用,因此您需要将TLine 限制为引用类型。
  • @Lee 我也不知道,您应该将其发布为答案,因为它解决了 OPs 问题;)

标签: c# generics


【解决方案1】:

您只需将class 约束添加到TLine

class Matrix<TLine> where TLine : class, ILine

这将确保TLine 是一个引用类型——然后允许泛型变体起作用。方差适用于引用类型,因为这样 CLR 就知道 TLine 类型的值可以用作 ILine 类型的值,而无需任何装箱或其他表示变化。 p>

【讨论】:

    猜你喜欢
    • 2015-10-28
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多