Groups | Blog | Home
all groups > dotnet general > december 2005 >

dotnet general : querying for properties that has implemented an attribute ?


Andreas Mueller
12/17/2005 4:50:49 PM
[quoted text, click to view]

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[i].GetCustomAttributes(typeof(MyAttrib), false);
for (int j = 0; j < attribs.Length; ++j)
{
if (attribType.IsAssignableFrom(attribs[j].GetType()))
{
props.Add(pis[i]);
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);
}
}
}
KK
12/17/2005 9:14:55 PM
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

AddThis Social Bookmark Button