简体   繁体   English

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

[英]How can I find the attributes of a generic class in C#?

I have the following classes: 我有以下课程:

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


public class HappyPerson
{
   ...
}

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

Using the following method I can get the attributes of the "PersonContainer": 使用以下方法,我可以获取“ 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();        
}

However I only get the attribute of "PersonContainer" (which is "YaaY") how can I get the atrributes of T (HappyPerson [if any] or SadPerson["NaaY"]) at runtime without knowing what T is? 但是,我仅获得“ PersonContainer”的属性(即“ YaaY”),如何在运行时获得T (HappyPerson [if any] or SadPerson["NaaY"])的属性T (HappyPerson [if any] or SadPerson["NaaY"])而又不知道T是什么?

You need to get generic argument's type and then it's attributes: 您需要获取通用参数的类型,然后是属性:

var info = personContainer.GetType();

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

Edit: GetGenericArguments returns a Type array so my first call to GetType was unnecessary and I remove it. 编辑: GetGenericArguments返回一个Type数组,因此我对GetType第一次调用是不必要的,因此将其删除。

You need to loop through the generic type arguments to get their attributes: 您需要遍历泛型类型参数以获取其属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM