我想用声明的参数名生成泛型类的名称。例如,如果我有通用类和实例化的类,如下所示,我想打印"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
答案 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);
}
}
}
希望有了这些信息,你可以自己计算字符串格式等。