【问题标题】:How to retrieve an attribute value along with a runtime property value如何检索属性值以及运行时属性值
【发布时间】:2012-01-18 04:11:26
【问题描述】:

我创建了一个自定义属性,用于我的班级MyClass。我希望能够反映此类的一个实例,以查看该属性的信息。

假设我有这个类定义:

public class MyClass
{
   [Example("MyClassID")]
   public string ID;
}

稍后在我的代码中,我使用了这个类的一个实例:

MyClass mc = new MyClass();
mc.ID = 18;

有没有办法从这个实例中获取属性值(“MyClassID”),mc?理想情况下,我希望能够以类似于以下方式将此与我的财产联系起来:

mc.ID.GetCustomAttributes(typeof(ExampleAttribute), false)

【问题讨论】:

    标签: .net reflection attributes


    【解决方案1】:

    是的,你可以通过反射来做到这一点:

    this.GetType().GetProperty("ID").GetCustomAttributes(typeof(ExampleAttribute))
    

    如果这不是一个属性(它不在您的示例中,但我不确定这是否是问题的函数),那么您可以使用 GetMember。

    【讨论】:

    • 这很棒。有没有更强类型的方法来获取 ID 属性?编译时支持会很棒(我知道考虑到反射的使用,这似乎是一个不切实际的要求)。
    • 不幸的是,目前我知道没有比这更强大的方法了。
    【解决方案2】:

    是的,您可以获得属性的值。这是一个例子:

     Type t = this.GetType();
     var id = t.GetProperty("ID");
     var attribute = id.GetCustomAttributes(typeof(ExampleAttribute), false).FirstOrDefault();
     if (attribute != null)
     {
           ExampleAttribute item = attribute as ExampleAttribute;
           //Do stuff with the attribute
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-17
      相关资源
      最近更新 更多