在C#中访问泛型类型的GenericTypeParameters

时间:2016-12-23 21:39:59

标签: c# generics types

我想用声明的参数名生成泛型类的名称。例如,如果我有通用类和实例化的类,如下所示,我想打印"MyClass<P1,M>"

class MyClass<P1, M1> {}
// ... some code removed here
var myInstance = new MyClass<int,string>();

现在我获取myInstance的类型信息,然后获取通用类型定义,如下所示:

// MyClass<int,string> type info here
var type = myInstance.GetType();
 // MyClass<P1, M1> type info here
var genericType = type.GetGenericTypeDefinition();

调试器显示genericType属性GenericTypeParameters,其中包含所有参数名称和类型信息。但是,我无法从我的C#代码访问该集合,并且将genericType转换为System.RuntimeType类不起作用,因为RuntimeType是内部的。

那么有没有办法以某种方式访问​​GenericTypeParameters属性或我在这里SOL? 环境VS2015,.NET 4.6.1

1 个答案:

答案 0 :(得分:5)

我认为您只是在寻找Type.GetGenericArguments,您应该在genericType而不是type上调用 - 此时,类型“参数”实际上是参数因为它是一个开放类型。

示例(为简单起见使用Dictionary<,>):

using System;
using System.Collections.Generic;

class Test
{
    static void Main()
    {
        var dictionary = new Dictionary<string, int>();
        var type = dictionary.GetType();
        var genericType = type.GetGenericTypeDefinition();
        foreach (var typeArgument in genericType.GetGenericArguments())
        {
            // TKey, then TValue
            Console.WriteLine(typeArgument);
        }
    }
}

希望有了这些信息,你可以自己计算字符串格式等。