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

标签 c# generics reflection

我有以下类(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/

相关文章:

c# - 引用同一程序集的不同版本

c# - 为什么 Direct2D 和 DirectWrite 不使用传统的 COM 对象?

c# - asp.net "The DefaultButton of ' Panel1 ' must be the ID of a control of type IButtonControl."错误

java - 泛型类型作为泛型类型参数

c# - 通用方法不是选择最具体的构造函数签名吗?

java - java中的不可变类

c# - 具有通用代码隐藏的 WPF UserControl

C# 泛型 : How can I use them generically?

c# - 如何在使用 NLua 运行的脚本中对 .NET 枚举执行按位或运算?

c# - 在反射方法调用中访问网络共享