Get value from custom attribute-decorated property

2020-06-09 07:41发布

问题:

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?

回答1:

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


回答2:

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

Call it this way:

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