querying for properties that has implemented an attribute ?

  • Thread starter Thread starter KK
  • Start date Start date
K

KK

Hi,

I apply a custom Attribute to several properties
in a class. There are about 15 of those. I want
to know how I can programatically get ONLY those
properties that I have applied my attribute.

What I want is rather than calling those 15 attributes
like;

Object.Prop1
Object.Prop2
Object.Prop3 etc..

Is there a way to call it using reflection

foreach (Property that implements MyCustomAttribute){
object.Call Property that implements attribute
}

Thanks
KK
 
KK said:
Hi,

I apply a custom Attribute to several properties
in a class. There are about 15 of those. I want
to know how I can programatically get ONLY those
properties that I have applied my attribute.

What I want is rather than calling those 15 attributes
like;

Object.Prop1
Object.Prop2
Object.Prop3 etc..

Is there a way to call it using reflection

foreach (Property that implements MyCustomAttribute){
object.Call Property that implements attribute
}

Thanks
KK

Here's an example
HTH,
Andy


using System;
using System.Collections.Generic;
using System.Reflection;

namespace Xox
{
class MyAttrib : Attribute { }
class XXX
{
[MyAttrib]
public int III
{
get { return 0; }
set { ; }
}
}
class Program
{
private static List<PropertyInfo> FindProps(Type tp, Type
attribType)
{
List<PropertyInfo> props = new List<PropertyInfo>();
PropertyInfo[] pis = tp.GetProperties();
for (int i = 0; i < pis.Length; ++i)
{
object[] attribs =
pis.GetCustomAttributes(typeof(MyAttrib), false);
for (int j = 0; j < attribs.Length; ++j)
{
if (attribType.IsAssignableFrom(attribs[j].GetType()))
{
props.Add(pis);
break;
}
}
}
return props;
}
static void Main(string[] args)
{
List<PropertyInfo> props = FindProps(typeof(XXX),
typeof(MyAttrib));

XXX objectInstance = new XXX();

// so something with the props;
foreach (PropertyInfo pi in props)
{
// try to set
if (pi.CanWrite)
pi.SetValue(objectInstance, 5, null);
// try read
int i = -1;
if(pi.CanRead)
i = (int)pi.GetValue(objectInstance, null);
}
}
}
}
 

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

Back
Top