我有以下类(class):
[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 [如果有] 或 SadPerson["NaaY"])
的属性运行时不知道 T 是什么?
最佳答案
你需要得到泛型参数的类型,然后是它的属性:
var info = personContainer.GetType();
if (info.IsGenericType)
{
var attributes = (MsgAttribute[])info.GetGenericArguments()[0]
.GetCustomAttributes(typeof(MsgAttribute), false);
}
编辑:GetGenericArguments
返回一个 Type
数组,所以我第一次调用 GetType
是不必要的,我将其删除。
关于c# - 如何在 C# 中找到泛型类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22459289/