1 // System.MonoCustomAttrs.cs
2 // Hooks into the runtime to get custom attributes for reflection handles
4 // Paolo Molaro (lupus@ximian.com)
6 // (c) 2002 Ximian, Inc.
9 using System.Reflection;
10 using System.Collections;
11 using System.Runtime.CompilerServices;
14 internal class MonoCustomAttrs {
16 static Hashtable handle_to_attrs = new Hashtable ();
18 [MethodImplAttribute(MethodImplOptions.InternalCall)]
19 internal static extern object[] GetCustomAttributes (ICustomAttributeProvider obj);
21 private static object[] from_cache (ICustomAttributeProvider obj) {
22 object[] res = (object[])handle_to_attrs [obj];
25 res = GetCustomAttributes (obj);
26 handle_to_attrs.Add (obj, res);
30 internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, Type attributeType, bool inherit) {
31 object[] res = from_cache (obj);
33 if (res.Length == 1 && (res[0].GetType () == attributeType || res[0].GetType().IsSubclassOf(attributeType)))
34 return (object[])res.Clone ();
35 ArrayList a = new ArrayList ();
36 Type btype = obj as Type;
38 foreach (object attr in res) {
39 if (attributeType.Equals (attr.GetType ()) || attr.GetType().IsSubclassOf(attributeType))
42 if (btype != null && ((btype = btype.BaseType) != null)) {
43 res = from_cache (btype);
47 } while (inherit && btype != null && ((btype = btype.BaseType) != null));
48 Attribute[] r = new Attribute [a.Count];
53 internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, bool inherit) {
54 Type btype = obj as Type;
55 if (!inherit || btype == null) {
56 return (Object[])from_cache (obj).Clone ();
58 ArrayList a = new ArrayList ();
59 a.AddRange (from_cache (obj));
60 while ((btype = btype.BaseType) != null) {
61 a.AddRange (from_cache (btype));
63 Attribute[] r = new Attribute [a.Count];
68 internal static bool IsDefined (ICustomAttributeProvider obj, Type attributeType, bool inherit) {
69 object[] res = from_cache (obj);
70 foreach (object attr in res) {
71 if (attributeType.Equals (attr.GetType ()))
74 Type btype = obj as Type;
75 if (inherit && (btype != null) && ((btype = btype.BaseType) != null))
76 return IsDefined (btype, attributeType, inherit);