[英]How can I find the attributes of a generic class in C#?
我有以下课程:
[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 (HappyPerson [if any] or SadPerson["NaaY"])
而又不知道T是什么?
您需要获取通用参数的类型,然后是属性:
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(...)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.