从自定义属性装饰的属性中获取价值? [英] Get value from custom attribute-decorated property?
问题描述
我写了一个自定义属性,用于类的某些成员上
I've written a custom attribute that I use on certain members of a class:
public class Dummy
{
[MyAttribute]
public string Foo { get; set; }
[MyAttribute]
public int Bar { get; set; }
}
我能够从类型中获取自定义属性并找到我的特定属性.我不知道该怎么做是获取分配的属性的值.当我获取Dummy的一个实例并将其(作为一个对象)传递给我的方法时,如何获取从.GetProperties()返回的PropertyInfo对象并获取分配给.Foo和.Bar的值?
I'm able to get the custom attributes from the type and find my specific attribute. What I can't figure out how to do is to get the values of the assigned properties. When I take an instance of Dummy and pass it (as an object) to my method, how can I take the PropertyInfo object I get back from .GetProperties() and get the values assigned to .Foo and .Bar?
我的问题是我不知道如何正确调用GetValue.
My problem is that I can't figure out how to properly call 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-对象与目标类型不匹配.如何构造此调用以获取此值?
However, when I do this, the prop.GetValue call gives me a TargetException - Object does not match target type. How do I structure this call to get this value?
推荐答案
您需要将对象本身传递给GetValue,而不是属性对象:
Your need to pass object itself to GetValue, not a property object:
var value = prop.GetValue(o, null);
还有另一件事-您不应使用.First(),而应使用.FirstOrDefault(),因为如果某些属性不包含任何属性,则代码将引发异常:
And one more thing - you should use not .First(), but .FirstOrDefault(), because your code will throw an exception, if some property does not contains any attributes:
object attr = (from row in propattr
where row.GetType() == typeof(MyAttribute)
select row)
.FirstOrDefault();
这篇关于从自定义属性装饰的属性中获取价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!