如何检索属性值以及运行时属性值

时间:2012-01-17 19:52:48

标签: .net reflection attributes

我已经在我的班级 MyClass 上创建了一个自定义属性。我希望能够反思这个类的实例,以查看该属性的信息。

假设我有这个类定义:

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

稍后在我的代码中,我正在使用此类的实例:

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

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

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

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

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

 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
 }
相关问题