列表和集合的通用约束

Twe*_*nty 2 c# generics constraints generic-constraints

我有一个通用方法,看起来像这样:

public int GetCount<T>(T collection) where T: ICollection
{
   return collection.Count;    
}
Run Code Online (Sandbox Code Playgroud)

现在我希望能够调用此方法,其中集合参数可以是 aList<T>或 a HashSet<T>。当前的代码无法满足这一要求,因为我想要传递的参数不继承该ICollection接口。现在有什么方法可以通过简单的约束来实现这一点吗?

Gle*_*leb 5

为什么不:

public int GetCount<T>(ICollection<T> collection)
{
   return collection.Count;    
}
Run Code Online (Sandbox Code Playgroud)

  • @HimBromBeere `typeof(ICollection) != typeof(ICollection&lt;T&gt;)` (4认同)