gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:29:22 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com