I have a class, lets call it Book with a property called Name. With that property, I have an attribute associated with it.
public class Book
{
[Author("AuthorName")]
public string Name
{
get; private set;
}
}
In my main method, I'm using reflection and wish to get key value pair of each attribute for each property. So in this example, I'd expect to see "Author" for attribute name and "AuthorName" for the attribute value.
Question: How do I get the attribute name and value on my properties using Reflection?
Just looking for the right place to put this piece of code.
let's say you have the following property:
And you want to get the ShortName value. You can do:
Or to make it general:
Usage:
or:
Necromancing.
For those that still have to maintain .NET 2.0, or those that want to do it without LINQ:
Example usage:
or simply
Use
typeof(Book).GetProperties()
to get an array ofPropertyInfo
instances. Then useGetCustomAttribute()
on eachPropertyInfo
to see if any of them have theAuthor
Attribute type. If they do, you can get the name of the property from the property info and the attribute values from the attribute.Something along these lines to scan a type for properties that have a specific attribute type and to return data in a dictionary (note that this can be made more dynamic by passing types into the routine):
If you mean "for attributes that take one parameter, list the attribute-names and the parameter-value", then this is easier in .NET 4.5 via the
CustomAttributeData
API:To get all attributes of a property in a dictionary use this:
remember to change to false to true if you want to include inheritted attributes as well.