我编写了一个我在类的某些成员上使用的自定义属性:
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 - 对象与目标类型不匹配。如何构建此调用以获取此值?