Get value from custom attribute-decorated property

2020-06-09 07:21发布

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; }
}

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?

EDIT:

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);
    }
}

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?

2条回答
我命由我不由天
2楼-- · 2020-06-09 08:03

Your need to pass object itself to GetValue, not a property object:

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

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();
查看更多
闹够了就滚
3楼-- · 2020-06-09 08:20

You get array of PropertyInfo using .GetProperties() and call PropertyInfo.GetValue Method on each

Call it this way:

var value = prop.GetValue(o, null);
查看更多
登录 后发表回答