I have produced a custom attribute which simply marks a classes property as being the ‘display name’. What I would like to do is find the property within a given class which has been marked with my attribute. As far as I know, the only way I can do this is to loop through each property (via reflection) and check what attributes it has assigned. Is there any easier/quicker way than this?
foreach (PropertyInfo property in myClassProperties)
{
//Get the alias attributes.
object[] attr=
property.GetCustomAttributes(typeof(DisplayField), true);
if(attr.Count() > 0)
{
// This is a display field!
}
}
Thanks
Well, it’s slightly simpler than checking all its attributes to find the one you want – you can ask any member whether it has a particular attribute using
IsDefined:Obviously you can cache that result on a per-type basis if you’re going to use it multiple times.