[英]What do nested generics in C# mean?
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 ? 这说明IEnumerable可以拥有本身就是KeyValuePair的泛型类型吗?
Thanks, 谢谢,
Scott 斯科特
Yes. 是。 The KeyValuePair type expects two generic type parameters. KeyValuePair类型需要两个泛型类型参数。 We can either populate them by pointing to concrete types: 我们可以通过指向具体类型来填充它们:
IEnumerable<KeyValuePair<string, int>>
Or we can populate them by using other generic parameters already specified by the outer class: 或者我们可以使用外部类已经指定的其他通用参数来填充它们:
class Dictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
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. 就像任何其他参数一样,您可以使用常量的硬编码值(或本例中的类型)或其他变量填充它。
Yes, this is "An IEnumerable of Key/Value pairs." 是的,这是“IEnumerable of Key / Value pair”。 It would be declared thusly: 它将如此宣布:
IEnumberable<KeyValuePair<string, string>> reallyComplicatedDictionary =
new IEnumerable<KeyValuePair<string, string>>();
Or similar. 或类似的。
About the only think I can think this particular usage would do is allow you to have a "dictionary" with repeated keys. 关于我认为这种特殊用法可以做的唯一想法是允许你有一个带有重复键的“字典”。
In a nut shell, it means that when you enumerate over that IEnumerable
, you're going to get KeyValuePair<TKey, TValue>
(for whatever types TKey
and TValue
are set to). 在坚果shell中,这意味着当你枚举IEnumerable
,你将得到KeyValuePair<TKey, TValue>
(对于TKey
和TValue
设置的任何类型)。
So, yes. 所以,是的。
Here 这里
IEnumerable<KeyValuePair<string, int>>
The IEnumerable itself is not a generic. IEnumerable本身不是通用的。 It knows that it is going to contain KeyValuePair. 它知道它将包含KeyValuePair。 Here KeyValuePair is the generic which can contain any 2 generic types. 这里KeyValuePair是通用的,可以包含任何2种泛型类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.