如何在c#中找到泛型类的属性?

本文关键字:泛型类 属性 | 更新日期: 2023-09-27 17:50:48

我有以下类:

[Msg(Value = "YaaY")]
public class PersonContainer<T>  where T : new()
{
   ...
}

public class HappyPerson
{
   ...
}
[Msg(Value = "NaaY")]
public class SadPerson
{
   ...
}

使用下面的方法我可以得到"PersonContainer"的属性:

public void GetMsgVals(object personContainer)
{
    var info = personContainer.GetType();
    var attributes = (MsgAttribute[])info.GetCustomAttributes(typeof(MsgAttribute), false);
    var vals= attributes.Select(a => a.Value).ToArray();        
}

然而,我只得到"PersonContainer"(这是"YaaY")的属性,我怎么能得到T (HappyPerson [if any] or SadPerson["NaaY"])的属性在运行时不知道T是什么?

如何在c#中找到泛型类的属性?

你需要得到泛型参数的类型,然后它的属性:

var info = personContainer.GetType();
if (info.IsGenericType)
{
     var attributes = (MsgAttribute[])info.GetGenericArguments()[0]
                      .GetCustomAttributes(typeof(MsgAttribute), false);
}

编辑:GetGenericArguments返回一个Type数组,所以我第一次调用GetType是不必要的,我删除了它。

您需要遍历泛型类型参数以获取它们的属性:

var info = personContainer.GetType();
foreach (var gta in info.GenericTypeArguments)
{
    // gta.GetCustomAttributes(...)
}