Tue Feb 19 20:34:35 CET 2002 Paolo Molaro <lupus@ximian.com>
[mono.git] / mcs / class / corlib / System / MonoCustomAttrs.cs
1 // System.MonoCustomAttrs.cs
2 // Hooks into the runtime to get custom attributes for reflection handles
3 //
4 // Paolo Molaro (lupus@ximian.com)
5 //
6 // (c) 2002 Ximian, Inc.
7
8 using System;
9 using System.Reflection;
10 using System.Collections;
11 using System.Runtime.CompilerServices;
12
13 namespace System {
14         internal class MonoCustomAttrs {
15
16                 static Hashtable handle_to_attrs = new Hashtable ();
17
18                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
19                 internal static extern object[] GetCustomAttributes (ICustomAttributeProvider obj);
20
21                 private static object[] from_cache (ICustomAttributeProvider obj) {
22                         object[] res = (object[])handle_to_attrs [obj];
23                         if (res != null)
24                                 return res;
25                         res = GetCustomAttributes (obj);
26                         handle_to_attrs.Add (obj, res);
27                         return res;
28                 }
29
30                 internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, Type attributeType, bool inherit) {
31                         // handle inherit
32                         object[] res = from_cache (obj);
33                         // shortcut
34                         if (res.Length == 1 && res[0].GetType () == attributeType)
35                                 return res;
36                         ArrayList a = new ArrayList ();
37                         foreach (object attr in res) {
38                                 if (attributeType.Equals (attr.GetType ()))
39                                         a.Add (attr);
40                         }
41                         return a.ToArray ();
42                 }
43
44                 internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, bool inherit) {
45                         // handle inherit
46                         return from_cache (obj);
47                 }
48                 internal static bool IsDefined (ICustomAttributeProvider obj, Type attributeType, bool inherit) {
49                         // handle inherit
50                         object[] res = from_cache (obj);
51                         foreach (object attr in res) {
52                                 if (attributeType.Equals (attr.GetType ()))
53                                         return true;
54                         }
55                         return false;
56                 }
57         }
58 }