c# - C# : restricting the type parameter to be a collection 中的泛型

标签 c# generics collections

我需要编写一个通用类,其中类型参数必须是实现 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/

相关文章:

c# - 无法保存数据 c# Windows 应用程序

c# - 下拉列表 ASP.NET MVC 不更新模型

c# - 为什么我必须在 assembly.GetType() 的参数中指定命名空间?

java - 当我们有 Map 时,为什么还需要 Set 呢?

java - 关于采集框架

c# - IEnumerable 和顺序

c# - LINQ to 实体查询,在使用导航属性之前检查 null

java - 如何检查 java 中的(未检查的)强制转换?

c# - 具有自引用类型约束的通用类

f# - F# 中的通用模块