简体   繁体   中英

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":

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?

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.

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(...)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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