5 // Miguel de Icaza (miguel@ximian.com)
6 // Daniel Stodden (stodden@in.tum.de)
7 // Dietmar Maurer (dietmar@ximian.com)
9 // (C) Ximian, Inc. http://www.ximian.com
13 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 using System.Reflection;
36 using System.Runtime.Serialization;
37 using System.Runtime.CompilerServices;
38 using System.Runtime.InteropServices;
43 [ClassInterface (ClassInterfaceType.AutoDual)]
46 [System.Runtime.InteropServices.ComVisible (true)]
49 public abstract class Delegate : ICloneable, ISerializable
51 #region Sync with object-internals.h
52 private IntPtr method_ptr;
53 private IntPtr invoke_impl;
54 private object m_target;
55 private IntPtr method;
56 private Type target_type;
57 private string method_name;
58 private IntPtr delegate_trampoline;
59 private MethodInfo method_info;
61 // Keep a ref of the MethodInfo passed to CreateDelegate.
62 // Used to keep DynamicMethods alive.
63 private MethodInfo original_method_info;
66 protected Delegate (object target, string method)
69 throw new ArgumentNullException ("target");
72 throw new ArgumentNullException ("method");
74 this.target_type = null;
75 this.method_ptr = IntPtr.Zero;
76 this.m_target = target;
77 this.method_name = method;
80 protected Delegate (Type target, string method)
83 throw new ArgumentNullException ("target");
86 throw new ArgumentNullException ("method");
88 this.target_type = target;
89 this.method_ptr = IntPtr.Zero;
91 this.method_name = method;
94 public MethodInfo Method {
100 public object Target {
110 [MethodImplAttribute (MethodImplOptions.InternalCall)]
111 internal static extern Delegate CreateDelegate_internal (Type type, object target, MethodInfo info);
113 [MethodImplAttribute (MethodImplOptions.InternalCall)]
114 internal extern void SetMulticastInvoke ();
116 private static bool arg_type_match (Type delArgType, Type argType) {
117 bool match = delArgType == argType;
120 // Delegate contravariance
122 if (!delArgType.IsValueType && (delArgType != typeof (ValueType)) && (argType.IsAssignableFrom (delArgType)))
134 static Delegate CreateDelegate (Type type, MethodInfo method, bool throwOnBindFailure)
137 throw new ArgumentNullException ("type");
140 throw new ArgumentNullException ("method");
142 if (!type.IsSubclassOf (typeof (MulticastDelegate)))
143 throw new ArgumentException ("type is not a subclass of Multicastdelegate");
146 if (!method.IsStatic)
147 if (throwOnBindFailure)
148 throw new ArgumentException ("The method should be static.", "method");
153 MethodInfo invoke = type.GetMethod ("Invoke");
155 // FIXME: Check the return type on the 1.0 profile as well
157 Type returnType = method.ReturnType;
158 Type delReturnType = invoke.ReturnType;
159 bool returnMatch = returnType == delReturnType;
162 // Delegate covariance
163 if (!delReturnType.IsValueType && (delReturnType != typeof (ValueType)) && (delReturnType.IsAssignableFrom (returnType)))
168 if (throwOnBindFailure)
169 throw new ArgumentException ("method return type is incompatible");
174 ParameterInfo[] delargs = invoke.GetParameters ();
175 ParameterInfo[] args = method.GetParameters ();
178 if (!method.IsStatic)
180 // Net 2.0 feature. The first argument of the delegate is passed
181 // as the 'this' argument to the method.
183 argLengthMatch = (args.Length + 1 == delargs.Length);
185 argLengthMatch = (args.Length == delargs.Length);
187 if (throwOnBindFailure)
188 throw new ArgumentException ("method argument length mismatch");
193 if (!method.IsStatic) {
194 // The first argument should match this
195 argsMatch = arg_type_match (delargs [0].ParameterType, method.DeclaringType);
196 for (int i = 0; i < args.Length; i++)
197 argsMatch &= arg_type_match (delargs [i + 1].ParameterType, args [i].ParameterType);
200 for (int i = 0; i < args.Length; i++)
201 argsMatch &= arg_type_match (delargs [i].ParameterType, args [i].ParameterType);
205 if (throwOnBindFailure)
206 throw new ArgumentException ("method arguments are incompatible");
210 Delegate d = CreateDelegate_internal (type, null, method);
211 d.original_method_info = method;
215 public static Delegate CreateDelegate (Type type, MethodInfo method) {
216 return CreateDelegate (type, method, true);
224 static Delegate CreateDelegate (Type type, object target, MethodInfo method, bool throwOnBindFailure)
227 throw new ArgumentNullException ("type");
230 throw new ArgumentNullException ("method");
232 if (!type.IsSubclassOf (typeof (MulticastDelegate)))
233 throw new ArgumentException ("type is not a subclass of Multicastdelegate");
235 Delegate d = CreateDelegate_internal (type, target, method);
236 d.original_method_info = method;
246 static Delegate CreateDelegate (Type type, object target, MethodInfo method) {
247 return CreateDelegate (type, target, method, true);
250 public static Delegate CreateDelegate (Type type, object target, string method)
252 return CreateDelegate(type, target, method, false);
260 static Delegate CreateDelegate (Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure)
263 throw new ArgumentNullException ("type");
266 throw new ArgumentNullException ("target");
269 throw new ArgumentNullException ("method");
271 if (!type.IsSubclassOf (typeof (MulticastDelegate)))
272 throw new ArgumentException ("type is not subclass of MulticastDelegate.");
274 ParameterInfo[] delargs = type.GetMethod ("Invoke").GetParameters ();
275 Type[] delargtypes = new Type [delargs.Length];
277 for (int i=0; i<delargs.Length; i++)
278 delargtypes [i] = delargs [i].ParameterType;
281 * FIXME: we should check the caller has reflection permission
282 * or if it lives in the same assembly...
284 BindingFlags flags = BindingFlags.ExactBinding | BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic;
286 flags |= BindingFlags.IgnoreCase;
287 MethodInfo info = target.GetMethod (method, flags, null, delargtypes, new ParameterModifier [0]);
290 if (throwOnBindFailure)
291 throw new ArgumentException ("Couldn't bind to method.");
296 return CreateDelegate_internal (type, null, info);
299 public static Delegate CreateDelegate (Type type, Type target, string method) {
300 return CreateDelegate (type, target, method, false, true);
304 public static Delegate CreateDelegate (Type type, Type target, string method, bool ignoreCase) {
305 return CreateDelegate (type, target, method, ignoreCase, true);
314 static Delegate CreateDelegate (Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure)
317 throw new ArgumentNullException ("type");
320 throw new ArgumentNullException ("target");
323 throw new ArgumentNullException ("method");
325 if (!type.IsSubclassOf (typeof (MulticastDelegate)))
326 throw new ArgumentException ("type");
328 ParameterInfo[] delargs = type.GetMethod ("Invoke").GetParameters ();
329 Type[] delargtypes = new Type [delargs.Length];
331 for (int i=0; i<delargs.Length; i++)
332 delargtypes [i] = delargs [i].ParameterType;
335 * FIXME: we should check the caller has reflection permission
336 * or if it lives in the same assembly...
338 BindingFlags flags = BindingFlags.ExactBinding | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
341 flags |= BindingFlags.IgnoreCase;
343 MethodInfo info = target.GetType ().GetMethod (method, flags, null, delargtypes, new ParameterModifier [0]);
346 if (throwOnBindFailure)
347 throw new ArgumentException ("Couldn't bind to method '" + method + "'.");
351 return CreateDelegate_internal (type, target, info);
354 public static Delegate CreateDelegate (Type type, object target, string method, bool ignoreCase) {
355 return CreateDelegate (type, target, method, ignoreCase, true);
359 public object DynamicInvoke (params object[] args)
361 public object DynamicInvoke (object[] args)
364 return DynamicInvokeImpl (args);
367 protected virtual object DynamicInvokeImpl (object[] args)
369 if (Method == null) {
370 Type[] mtypes = new Type [args.Length];
371 for (int i = 0; i < args.Length; ++i) {
372 mtypes [i] = args [i].GetType ();
374 method_info = m_target.GetType ().GetMethod (method_name, mtypes);
378 if ((m_target != null) && Method.IsStatic) {
379 // The delegate is bound to m_target
381 object[] newArgs = new object [args.Length + 1];
382 args.CopyTo (newArgs, 1);
383 newArgs [0] = m_target;
386 args = new object [] { m_target };
388 return Method.Invoke (null, args);
392 return Method.Invoke (m_target, args);
395 public virtual object Clone ()
397 return MemberwiseClone ();
400 public override bool Equals (object obj)
402 Delegate d = obj as Delegate;
407 // Do not compare method_ptr, since it can point to a trampoline
408 if ((d.target_type == target_type) && (d.m_target == m_target) &&
409 (d.method_name == method_name) && (d.method_info == method_info))
415 public override int GetHashCode ()
417 // FIXME: Sync with Equals above
418 return (int)method_ptr;
421 protected virtual MethodInfo GetMethodImpl ()
426 // This is from ISerializable
427 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
429 DelegateSerializationHolder.GetDelegateData (this, info, context);
432 public virtual Delegate[] GetInvocationList()
434 return new Delegate[] { this };
438 /// Returns a new MulticastDelegate holding the
439 /// concatenated invocation lists of MulticastDelegates a and b
441 public static Delegate Combine (Delegate a, Delegate b)
451 if (a.GetType () != b.GetType ())
452 throw new ArgumentException (Locale.GetText ("Incompatible Delegate Types."));
454 return a.CombineImpl (b);
458 /// Returns a new MulticastDelegate holding the
459 /// concatenated invocation lists of an Array of MulticastDelegates
462 [System.Runtime.InteropServices.ComVisible (true)]
463 public static Delegate Combine (params Delegate[] delegates)
465 public static Delegate Combine (Delegate[] delegates)
468 if (delegates == null)
471 Delegate retval = null;
473 foreach (Delegate next in delegates)
474 retval = Combine (retval, next);
479 protected virtual Delegate CombineImpl (Delegate d)
481 throw new MulticastNotSupportedException (String.Empty);
484 public static Delegate Remove (Delegate source, Delegate value)
489 return source.RemoveImpl (value);
492 protected virtual Delegate RemoveImpl (Delegate d)
500 public static Delegate RemoveAll (Delegate source, Delegate value)
502 Delegate tmp = source;
503 while ((source = Delegate.Remove (source, value)) != tmp)
509 public static bool operator == (Delegate a, Delegate b)
511 if ((object)a == null) {
512 if ((object)b == null)
515 } else if ((object) b == null)
521 public static bool operator != (Delegate a, Delegate b)