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

Opt*_*ion 3 c# generics types

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

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

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

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

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

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

Jon*_*eet 5

我认为你只是在找Type.GetGenericArguments,你应该调用genericType而不是type- 在这一点上,类型"arguments"实际上是类型参数,因为它是一个开放类型.

样本(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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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