我需要编写一个通用类,其中类型参数必须是实现 ICollection<T>
的东西. MyClass
内部我需要集合的项目类型(在标记为 ???
的代码片段中)。
class MyClass<TCollection> where TCollection : ICollection<???>
{
// ...
public void store(??? obj) { /* put obj into collection */ }
// ...
}
通常集合实际上是一本字典。有时,它会像列表一样简单。
我完全知道如何在 C++ 中执行此操作。我将如何做到这一点是 C#?
最佳答案
好吧,您通常会使用另一个类型参数来执行此操作:
class MyClass<TCollection, TElement> where TCollection : ICollection<TElement>
{
// ...
public void store(TElement obj) { }
// ...
}
在这种情况下你真的需要 TCollection
吗?你能用 TElement
凑合一下吗?
关于c# - C# : restricting the type parameter to be a collection 中的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1642785/