从自定义属性装饰的属性中获取值?

12

我写了一个自定义属性,我在类的某些成员上使用它:

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——对象与目标类型不匹配。如何构造这个调用以获取这个值?

2个回答

12

您需要将对象本身传递给 GetValue,而不是一个属性对象:

var value = prop.GetValue(o, null);

还有一件事 - 你应该使用 .FirstOrDefault() 而不是 .First(),因为如果某些属性不包含任何属性,你的代码将抛出异常:

object attr = (from row in propattr 
               where row.GetType() == typeof(MyAttribute) 
               select row)
              .FirstOrDefault();

同意使用FirstOrDefault--这只是一个编造的例子,用来演示问题,但感谢您的帮助。晕,竟然不敢相信就是这个问题。 - Joe

3

您可以使用.GetProperties()方法获取PropertyInfo数组,并对每个属性调用PropertyInfo.GetValue方法。

调用方式如下:

var value = prop.GetValue(o, null);

澄清一下:为了从 Dummy 类中获取属性值,OP 需要一个实例。仅有一个类型是不够的。 - KeithS
我已经更新了我的问题 - 我的问题确切地在于.GetValue以及如何调用它使其正常工作。 - Joe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接