【问题标题】:Get value from custom attribute-decorated property?从自定义属性装饰的属性中获取价值?
【发布时间】:2011-02-03 23:54:24
【问题描述】:

我编写了一个自定义属性,用于类的某些成员:

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

【问题讨论】:

    标签: c# .net custom-properties


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 同意 FirstOrDefault -- 这主要是一个人为的例子来演示问题,但感谢您的帮助。呃,简直不敢相信就是这样。
    【解决方案2】:

    您使用.GetProperties() 获得PropertyInfo 数组并在每个上调用PropertyInfo.GetValue 方法

    这样称呼:

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

    【讨论】:

    • 澄清一下; OP 需要一个 Dummy 类的实例才能从中获取属性值。一个 Type 本身是不够的。
    • 我已经更新了我的问题——我的问题完全在于 .GetValue 以及如何调用它以使其真正起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 2011-03-18
    • 2013-04-10
    • 2013-05-30
    相关资源
    最近更新 更多