C# 中的嵌套泛型是什么意思?
这是一个基本问题,但似乎仍然难倒了我。
给定“嵌套泛型”:
IEnumerable<KeyValuePair<TKey, TValue>>
这是否表明 IEnumerable 可以具有本身为 KeyValuePair 的泛型类型?
谢谢,
斯科特
A bit of a basic question, but one that seems to stump me, nonetheless.
Given a "nested generic":
IEnumerable<KeyValuePair<TKey, TValue>>
Is this stating that IEnumerable can have generic types that are themselves KeyValuePair 's ?
Thanks,
Scott
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的。 KeyValuePair 类型需要两个泛型类型参数。我们可以通过指向具体类型来填充它们:
或者我们可以通过使用外部类已经指定的其他泛型参数来填充它们:
泛型类型参数始终在“使用时”指定,或者在您使用该类时指定或需要它们的方法。就像任何其他参数一样,您可以用常量、硬编码值(或本例中的类型)或其他变量填充它。
Yes. The KeyValuePair type expects two generic type parameters. We can either populate them by pointing to concrete types:
Or we can populate them by using other generic parameters already specified by the outer class:
Generic type parameters are always specified "at-use", or at the point where you are using the class or method that requires them. And just like any other parameter, you can fill it with a constant, hard-coded value (or type in this case), or another variable.
是的,这是“Key/Value 对的 IEnumerable”。它将这样声明:
或类似的。
我唯一能想到的就是这种特殊用法可以让你拥有一个带有重复键的“字典”。
Yes, this is "An IEnumerable of Key/Value pairs." It would be declared thusly:
Or similar.
About the only think I can think this particular usage would do is allow you to have a "dictionary" with repeated keys.
简而言之,这意味着当您枚举
IEnumerable
时,您将获得KeyValuePair
(对于任何类型TKey< /code> 和
TValue
设置为)。所以,是的。
In a nut shell, it means that when you enumerate over that
IEnumerable
, you're going to getKeyValuePair<TKey, TValue>
(for whatever typesTKey
andTValue
are set to).So, yes.
这里
IEnumerable 本身不是泛型。它知道它将包含 KeyValuePair。这里的 KeyValuePair 是泛型,可以包含任意 2 个泛型类型。
Here
The IEnumerable itself is not a generic. It knows that it is going to contain KeyValuePair. Here KeyValuePair is the generic which can contain any 2 generic types.