2

给定以下示例,我收到以下编译器错误:
Cannot apply operator '==' to type 'TEnumerable' and 'TEnumerable'

class MyClass<TEnumerable, TItem> where TEnumerable : IEnumerable<TItem>
{
  public void DoSomething(TEnumerable item)
  {
    if (item == default(TEnumerable)) return; // Compiler error here
  }
}

当我添加class约束

class MyClass<TEnumerable, TItem> where TEnumerable : class, IEnumerable<TItem>

它按预期编译。


根据 MSDN,class约束意味着:

类型参数必须是引用类型;这也适用于任何类、接口、委托或数组类型。

但是IEnumerable<TItem>已经是一个reference type(所有接口都是引用类型),所以class约束没有增加进一步的限制。所以我的问题是:为什么我需要这个约束?

4

0 回答 0