I noticed that objects which take custom attributes implement ICustomAttributeProvider. There is a GetCustomAttributes(Type, Boolean) overload which will get the custom attributes of a specific type, but I like the generic syntax better. I also prefer to return an IList rather than an array, but I don't really have any reasons for or against this preference.
I wrote a generic extension method for anything that is an ICustomAttributeProvider that will return a strongly typed list of attributes on the object:
public static List<T> GetAttributes<T>(this ICustomAttributeProvider pi)The usage is pretty cut and dry, but you can reference the afore mentioned article: Validate Parameters Using Attributes and PostSharp
where T : Attribute
{
List<T> attrs = new List<T>();
foreach (object a in pi.GetCustomAttributes(typeof(T), false))
if (a is T) attrs.Add(a as T);
return attrs;
}
I really appreciate comments so please feel free to comment on my posts. Whether you agree or disagree, I'd love to hear from you. Also, feel free to link back to your own blog in your comments. You can even subscribe to an RSS feed of the comments on this thread.
© 2008 , D. Patrick Caldwell, President, Autopilot Consulting, LLC
© 2008 , D. Patrick Caldwell, President, Autopilot Consulting, LLC
click for more information
No comments:
Post a Comment