namespace GenericsTest
{
public class AGenericClass<T>
{
public class NestedNonGenericClass
{
}
}
}
在上面的例子中,应该NestedNonGenericClass
被认为是泛型类?
反射 API 说它是一个泛型类,甚至把包含类的模板参数作为嵌套类的模板参数交给我。
Type nestedClass = typeof(AGenericClass<int>.NestedNonGenericClass);
Console.Out.WriteLine("IsGeneric: {0}\tHasGenericArguments: {1}",
nestedClass.IsGenericType, nestedClass.GetGenericArguments().Length > 0);
打印出来:
IsGeneric: True HasGenericArguments: True
我不完全同意这种行为。即使编译器为 NestedNonGenericClass
生成泛型类型,我想知道它是通用的,因为它是这样声明的,还是因为它的容器是通用的。
所以,我的问题是:
首先,您认为考虑嵌套类泛型是可以的,因为它的容器是泛型的吗?为什么/为什么不?
其次,您是否碰巧知道一些其他 API 可以帮助我仅识别声明为通用的类?
P.S:我在 ECMA 泛型规范中找不到与此相关的任何内容(或者我可能只是掩盖了它)。
--编辑--
为了添加更多上下文,我正在研究一种代码生成器。我正在使用反射 API 来确定一个类型是否是通用的。
我遇到了 Dictionary<TKey, TValue>.KeyCollection
的问题.
对于 KeyCollection
, 反射 API 说它是通用的并交给我 TKey
和 TValue
在容器中声明的。因此,生成器最终生成 Dictionary<TKey, TValue>.KeyCollection<Tkey, TValue>
我能解决这个问题的唯一方法是将嵌套类的模板参数与容器的模板参数进行匹配,并消除所有匹配的参数。但我想知道是否有更好的方法。
最佳答案
简而言之,是的——一个类型从包含它的任何类型继承类型参数:这是像 List<T>.Enumerator
这样的事情的关键。和许多其他场景等 - 他们共享 T
至关重要来自外部类(不只是任何 T
)。
ECMA 引用文献是 §25.1:
Any class nested inside a generic class declaration or a generic struct declaration (§25.2) is itself a generic class declaration, since type parameters for the containing type shall be supplied to create a constructed type.
关于C#:泛型类中的嵌套类是否应该被视为泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/486917/