[英]Get value from custom attribute-decorated property?
我编写了一个我在类的某些成员上使用的自定义属性:
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(),因为你的代码会抛出异常,如果某些属性不包含任何属性:
object attr = (from row in propattr
where row.GetType() == typeof(MyAttribute)
select row)
.FirstOrDefault();
使用.GetProperties()
获取PropertyInfo
数组,并在每个上调用PropertyInfo.GetValue方法
这样称呼它:
var value = prop.GetValue(o, null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.