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