2

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

public int GetCount<T>(T collection) where T: ICollection
{
   return collection.Count;    
}

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

4

1 回答 1

4

为什么不:

public int GetCount<T>(ICollection<T> collection)
{
   return collection.Count;    
}
于 2019-12-13T11:29:24.953 回答