我有一个类:
class MyClass
{
public static class MyNestedClass
{
public const int M1 = 1;
public const int M2 = 2;
}
}
class MyClass2
{
public static class MyNestedClass
{
public const int M1 = 1;
public const int M2 = 2;
}
}
和一个通用函数:
private static void Work<T>()
{
Type myType = typeof(T.MyNestedClass);
myType.GetFields().Select(....);
// .. use T here as well..
}
我收到错误:error CS0704: Cannot do member lookup in 'T' because it is a type parameter
。
因为 MyNestedClass
是静态类,当我尝试将它作为另一个通用类型参数传递时:
private static void Work<T, S>()
{
Type myType = typeof(S);
myType.GetFields().Select(....);
// .. use T here as well..
}
调用方式,
Work<MyClass, MyClass.MyNestedClass>();
给我错误:静态类型不能用作类型参数
在 C# 中访问嵌套静态和非静态类的正确方法是什么?
最佳答案
T
类型没有名为 MyNestedClass
的嵌套类型,除非您指定 T
实际上是一个 MyClass
。然后,您可以使用 GetNestedTypes()
方法检索嵌套类型:
private static void Work<T>() where T : MyClass
{
Type myType = typeof(T).GetNestedTypes().FirstOrDefault();
//...
}
GetNestedType
方法也可以接受类型名称 string
。
但是您不能使用约束来强制特定类型具有嵌套类型。
关于c# - 访问泛型类型的静态嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50858958/