我编写了一个自定义属性,用于类的某些成员:
public class Dummy
{
[MyAttribute]
public string Foo { get; set; }
[MyAttribute]
public int Bar { get; set; }
}
我可以从类型中获取自定义属性并找到我的特定属性。我不知道如何获取指定属性的值。当我获取 Dummy 的实例并将其(作为对象)传递给我的方法时,如何获取从 .GetProperties() 返回的 PropertyInfo 对象并获取分配给 .Foo 和 .Bar 的值?
EDIT:
我的问题是我不知道如何正确调用 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);
还有一件事 - 您不应该使用 .First(),而是使用 .FirstOrDefault(),因为如果某些属性不包含任何属性,您的代码将引发异常:
object attr = (from row in propattr
where row.GetType() == typeof(MyAttribute)
select row)
.FirstOrDefault();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)