如何在C#中找到泛型类的属性?
我有以下课程:如何在C#中找到泛型类的属性?,c#,generics,reflection,C#,Generics,Reflection,我有以下课程: [Msg(Value = "YaaY")] public class PersonContainer<T> where T : new() { ... } public class HappyPerson { ... } [Msg(Value = "NaaY")] public class SadPerson { ... } 但是,我只获得“PersonContainer”(即“YaaY”)的属性如何在运行时获得T(HappyPerson[
[Msg(Value = "YaaY")]
public class PersonContainer<T> where T : new()
{
...
}
public class HappyPerson
{
...
}
[Msg(Value = "NaaY")]
public class SadPerson
{
...
}
但是,我只获得“PersonContainer”(即“YaaY”)的属性如何在运行时获得
T(HappyPerson[if any]或SadPerson[“NaaY”])
的属性,而不知道T是什么?您需要获得泛型参数的类型以及它的属性:
var info = personContainer.GetType();
if (info.IsGenericType)
{
var attributes = (MsgAttribute[])info.GetGenericArguments()[0]
.GetCustomAttributes(typeof(MsgAttribute), false);
}
var info = personContainer.GetType();
foreach (var gta in info.GenericTypeArguments)
{
// gta.GetCustomAttributes(...)
}
编辑:
GetGenericArguments
返回一个Type
数组,因此我对GetType
的第一次调用是不必要的,我将其删除。您需要获取泛型参数的类型,然后是它的属性:
var info = personContainer.GetType();
if (info.IsGenericType)
{
var attributes = (MsgAttribute[])info.GetGenericArguments()[0]
.GetCustomAttributes(typeof(MsgAttribute), false);
}
var info = personContainer.GetType();
foreach (var gta in info.GenericTypeArguments)
{
// gta.GetCustomAttributes(...)
}
编辑:
GetGenericArguments
返回一个Type
数组,因此我对GetType
的第一次调用是不必要的,我将其删除。您需要循环遍历泛型类型参数以获取其属性:
var info = personContainer.GetType();
if (info.IsGenericType)
{
var attributes = (MsgAttribute[])info.GetGenericArguments()[0]
.GetCustomAttributes(typeof(MsgAttribute), false);
}
var info = personContainer.GetType();
foreach (var gta in info.GenericTypeArguments)
{
// gta.GetCustomAttributes(...)
}
您需要循环遍历泛型类型参数以获取其属性:
var info = personContainer.GetType();
if (info.IsGenericType)
{
var attributes = (MsgAttribute[])info.GetGenericArguments()[0]
.GetCustomAttributes(typeof(MsgAttribute), false);
}
var info = personContainer.GetType();
foreach (var gta in info.GenericTypeArguments)
{
// gta.GetCustomAttributes(...)
}
可能重复的可能重复的可能重复的谢谢你的回答。谢谢你的回答。