[英]C# get generic parameter name using reflection
say that I have a C# class like this: 说我有一个像这样的C#类:
class MyClass<Tkey,Tvalue>{}
How do I get "Tkey"
and "Tvalue"
from given Type instance? 如何从给定的Type实例中获取
"Tkey"
和"Tvalue"
? I need the parameter name, not Type. 我需要参数名称,而不是Type。
EDIT My class is of unknown type, so it can be something like 编辑我的类是未知类型,所以它可能是类似的
class MyClass2<Ttype>{}
as well 同样
You first have to use the method GetGenericTypeDefinition()
on the Type to get another Type that represents the generic template. 首先必须在Type上使用方法
GetGenericTypeDefinition()
来获取另一个表示通用模板的Type。 Then you can use GetGenericArguments()
on that to receive the definition of the original placeholders including their names. 然后,您可以在其上使用
GetGenericArguments()
来接收原始占位符的定义,包括它们的名称。
For example: 例如:
class MyClass<Tkey, Tvalue> { };
private IEnumerable<string> GetTypeParameterNames(Type fType)
{
List<string> result = new List<string>();
if(fType.IsGenericType)
{
var lGenericTypeDefinition = fType.GetGenericTypeDefinition();
foreach(var lGenericArgument in lGenericTypeDefinition.GetGenericArguments())
{
result.Add(lGenericArgument.Name);
}
}
return result;
}
private void AnalyseObject(object Object)
{
if (Object != null)
{
var lTypeParameterNames = GetTypeParameterNames(Object.GetType());
foreach (var name in lTypeParameterNames)
{
textBox1.AppendText(name + Environment.NewLine);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
var object1 = new MyClass<string, string>();
AnalyseObject(object1);
var object2 = new List<string>();
AnalyseObject(object2);
AnalyseObject("SomeString");
}
You can use Type.GetGenericArguments
to get the Types. 您可以使用
Type.GetGenericArguments
来获取类型。 From them you can select the name: 从中他们可以选择名称:
IEnumerable<string> genericParameterNames = instance.GetType().GetGenericArguments().Select(t => t.Name);
Edit : 编辑 :
To get the names of the generic arguments, you should have a look at NineBerry's answer . 要获取泛型参数的名称 ,您应该看一下NineBerry的答案 。 A simplified version of it is this:
它的简化版本是这样的:
IEnumerable<string> genericParameterNames = instance.GetType()
.GetGenericTypeDefinition()
.GetGenericArguments()
.Select(t => t.Name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.