从自定义属性装饰属性获取价值?

我编写了一个我在类的某些成员上使用的自定义属性:

public class Dummy { [MyAttribute] public string Foo { get; set; } [MyAttribute] public int Bar { get; set; } } 

我能够从类型中获取自定义属性并找到我的特定属性。 我无法弄清楚怎么做是获取指定属性的值。 当我获取Dummy的实例并将其作为对象传递给我的方法时,如何获取我从.GetProperties()获取的PropertyInfo对象并获取分配给.Foo和.Bar的值?

编辑:

我的问题是我无法弄清楚如何正确调用GetValue。

 void TestMethod (object o) { Type t = o.GetType(); var props = t.GetProperties(); foreach (var prop in props) { var propattr = prop.GetCustomAttributes(false); object attr = (from row in propattr where row.GetType() == typeof(MyAttribute) select row).First(); if (attr == null) continue; MyAttribute myattr = (MyAttribute)attr; var value = prop.GetValue(prop, null); } } 

但是,当我这样做时,prop.GetValue调用给了我一个TargetException – 对象与目标类型不匹配。 如何构建此调用以获取此值?

您需要将对象本身传递给GetValue,而不是属性对象:

 var value = prop.GetValue(o, null); 

还有一件事 – 你应该使用notFirst(),但是.FirstOrDefault(),因为你的代码会抛出exception,如果某些属性不包含任何属性:

 object attr = (from row in propattr where row.GetType() == typeof(MyAttribute) select row) .FirstOrDefault(); 

使用.GetProperties()获取PropertyInfo数组,并在每个上调用PropertyInfo.GetValue方法

这样称呼它:

 var value = prop.GetValue(o, null);