C#中的泛型类型:将类型参数限制为集合

sbi*_*sbi 3 c# generics collections

我需要编写一个泛型类,其中type参数必须是实现的东西ICollection<T>.在里面MyClass我需要集合的项目类型(在标记为的代码片段中???).

class MyClass<TCollection> where TCollection : ICollection<???>
{
  // ...

  public void store(??? obj) { /* put obj into collection */ }

  // ...
}
Run Code Online (Sandbox Code Playgroud)

通常该集合实际上是字典.有时,它会像列表一样简单.

我确切知道如何在C++中执行此操作.我怎么做这个是C#?

Jon*_*eet 5

好吧,你通常使用另一个类型参数:

class MyClass<TCollection, TElement> where TCollection : ICollection<TElement>
{
  // ...

  public void store(TElement obj) { }

  // ...
}
Run Code Online (Sandbox Code Playgroud)

TCollection在这种情况下你真的需要吗?你能搞定TElement吗?