我有一个班级:
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
是静态类,当我尝试将其作为另一个Generic Type参数传递为:
private static void Work<T, S>()
{
Type myType = typeof(S);
myType.GetFields().Select(....);
// .. use T here as well..
}
通过调用,
Work<MyClass, MyClass.MyNestedClass>();
给我错误:static types cannot be used as type arguments
在c#中访问嵌套的静态和非静态类的正确方法是什么?
答案 0 :(得分:2)
类型T
没有名为MyNestedClass
的嵌套类型,除非您指定T
实际为MyClass
。然后,您可以使用GetNestedTypes()
方法检索嵌套类型:
private static void Work<T>() where T : MyClass
{
Type myType = typeof(T).GetNestedTypes().FirstOrDefault();
//...
}
有一个GetNestedType
方法可以接受类型名称string
。
但您不能使用约束来强制使用特定类型来拥有嵌套类型。