访问泛型类型的静态嵌套类

时间:2018-06-14 13:41:58

标签: c# generics

我有一个班级:

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#中访问嵌套的静态和非静态类的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

类型T没有名为MyNestedClass的嵌套类型,除非您指定T实际为MyClass。然后,您可以使用GetNestedTypes()方法检索嵌套类型:

private static void Work<T>() where T : MyClass
{
    Type myType = typeof(T).GetNestedTypes().FirstOrDefault();
    //...
}

有一个GetNestedType方法可以接受类型名称string

但您不能使用约束来强制使用特定类型来拥有嵌套类型。

相关问题