Reflection and Attributes

J

Jon Turner

Given an object/class, how do I (using reflection) get a list of properties that have a specific attribute assigned to them ? In this example, I want to obtain a list of all propertiesthat have the attribute 'FooAttribute' assigned to them. Many TIA[AttributeUsage( AttributeTargets.Property)]public class FooAttribute:Attribute{ bool _isFooBarred; FooAttribute() { _isFooBarred = false;}}public class Foo{ [FooAttribute()] public byte Property1 { get{}; set{}; } [FooAttribute()] public int Property2 { get{}; set{}; } public string Property3 { get{}; set{}; }}
 
S

Siva M

Here is one way to accomplish:

Type t = typeof (Foo);
MemberInfo[] mi = t.GetMembers(BindingFlags.GetProperty);
foreach (MemberInfo m in mi)
{
if (m.GetCustomAttributes(typeof(FooAttribute), false).Length > 0)
{
// FooAttribute defined for this property
}
}
Given an object/class, how do I (using reflection) get a list of properties that have a specific attribute assigned to them ? In this example, I want to obtain a list of all propertiesthat have the attribute 'FooAttribute' assigned to them. Many TIA [AttributeUsage( AttributeTargets.Property)]public class FooAttribute:Attribute{ bool _isFooBarred; FooAttribute() { _isFooBarred = false;}} public class Foo{ [FooAttribute()] public byte Property1 { get{}; set{}; } [FooAttribute()] public int Property2 { get{}; set{}; } public string Property3 { get{}; set{}; }}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top