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.Remoting;
37 using System.Runtime.Serialization;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
43 /* Contains the rarely used fields of Delegate */
45 public Type target_type;
46 public string method_name;
49 [ClassInterface (ClassInterfaceType.AutoDual)]
50 [System.Runtime.InteropServices.ComVisible (true)]
52 public abstract class Delegate : ICloneable, ISerializable
54 #region Sync with object-internals.h
55 #pragma warning disable 169, 414, 649
56 private IntPtr method_ptr;
57 private IntPtr invoke_impl;
58 private object m_target;
59 private IntPtr method;
60 private IntPtr delegate_trampoline;
61 private IntPtr method_code;
62 private MethodInfo method_info;
64 // Keep a ref of the MethodInfo passed to CreateDelegate.
65 // Used to keep DynamicMethods alive.
66 private MethodInfo original_method_info;
68 private DelegateData data;
69 #pragma warning restore 169, 414, 649
72 protected Delegate (object target, string method)
75 throw new ArgumentNullException ("target");
78 throw new ArgumentNullException ("method");
80 this.m_target = target;
81 this.data = new DelegateData ();
82 this.data.method_name = method;
85 protected Delegate (Type target, string method)
88 throw new ArgumentNullException ("target");
91 throw new ArgumentNullException ("method");
93 this.data = new DelegateData ();
94 this.data.method_name = method;
95 this.data.target_type = target;
98 public MethodInfo Method {
100 if (method_info != null) {
103 if (method != IntPtr.Zero) {
104 method_info = (MethodInfo)MethodBase.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (method));
111 public object Target {
121 [MethodImplAttribute (MethodImplOptions.InternalCall)]
122 internal static extern Delegate CreateDelegate_internal (Type type, object target, MethodInfo info, bool throwOnBindFailure);
124 [MethodImplAttribute (MethodImplOptions.InternalCall)]
125 internal extern void SetMulticastInvoke ();
127 private static bool arg_type_match (Type delArgType, Type argType) {
128 bool match = delArgType == argType;
130 // Delegate contravariance
132 if (!argType.IsValueType && argType.IsAssignableFrom (delArgType))
139 private static bool return_type_match (Type delReturnType, Type returnType) {
140 bool returnMatch = returnType == delReturnType;
143 // Delegate covariance
144 if (!returnType.IsValueType && delReturnType.IsAssignableFrom (returnType))
151 public static Delegate CreateDelegate (Type type, object firstArgument, MethodInfo method, bool throwOnBindFailure)
153 // The name of the parameter changed in 2.0
154 object target = firstArgument;
157 throw new ArgumentNullException ("type");
160 throw new ArgumentNullException ("method");
162 if (!type.IsSubclassOf (typeof (MulticastDelegate)))
163 throw new ArgumentException ("type is not a subclass of Multicastdelegate");
165 MethodInfo invoke = type.GetMethod ("Invoke");
167 if (!return_type_match (invoke.ReturnType, method.ReturnType))
168 if (throwOnBindFailure)
169 throw new ArgumentException ("method return type is incompatible");
173 ParameterInfo[] delargs = invoke.GetParameters ();
174 ParameterInfo[] args = method.GetParameters ();
178 if (target != null) {
179 // delegate closed over target
180 if (!method.IsStatic)
181 // target is passed as this
182 argLengthMatch = (args.Length == delargs.Length);
184 // target is passed as the first argument to the static method
185 argLengthMatch = (args.Length == delargs.Length + 1);
187 if (!method.IsStatic)
189 // Net 2.0 feature. The first argument of the delegate is passed
190 // as the 'this' argument to the method.
192 argLengthMatch = (args.Length + 1 == delargs.Length);
194 argLengthMatch = (args.Length == delargs.Length);
197 // closed over a null reference
198 argLengthMatch = args.Length == delargs.Length + 1;
202 if (throwOnBindFailure)
203 throw new ArgumentException ("method argument length mismatch");
208 if (target != null) {
209 if (!method.IsStatic) {
210 argsMatch = arg_type_match (target.GetType (), method.DeclaringType);
211 for (int i = 0; i < args.Length; i++)
212 argsMatch &= arg_type_match (delargs [i].ParameterType, args [i].ParameterType);
214 argsMatch = arg_type_match (target.GetType (), args [0].ParameterType);
215 for (int i = 1; i < args.Length; i++)
216 argsMatch &= arg_type_match (delargs [i - 1].ParameterType, args [i].ParameterType);
219 if (!method.IsStatic) {
220 // The first argument should match this
221 argsMatch = arg_type_match (delargs [0].ParameterType, method.DeclaringType);
222 for (int i = 0; i < args.Length; i++)
223 argsMatch &= arg_type_match (delargs [i + 1].ParameterType, args [i].ParameterType);
225 if (delargs.Length + 1 == args.Length) {
226 // closed over a null reference
227 argsMatch = !args [0].ParameterType.IsValueType;
228 for (int i = 0; i < delargs.Length; i++)
229 argsMatch &= arg_type_match (delargs [i].ParameterType, args [i + 1].ParameterType);
232 for (int i = 0; i < args.Length; i++)
233 argsMatch &= arg_type_match (delargs [i].ParameterType, args [i].ParameterType);
239 if (throwOnBindFailure)
240 throw new ArgumentException ("method arguments are incompatible");
244 Delegate d = CreateDelegate_internal (type, target, method, throwOnBindFailure);
246 d.original_method_info = method;
250 public static Delegate CreateDelegate (Type type, object firstArgument, MethodInfo method) {
251 return CreateDelegate (type, firstArgument, method, true);
254 public static Delegate CreateDelegate (Type type, MethodInfo method, bool throwOnBindFailure)
256 return CreateDelegate (type, null, method, throwOnBindFailure);
259 public static Delegate CreateDelegate (Type type, MethodInfo method) {
260 return CreateDelegate (type, method, true);
263 public static Delegate CreateDelegate (Type type, object target, string method)
265 return CreateDelegate(type, target, method, false);
268 static MethodInfo GetCandidateMethod (Type type, Type target, string method, BindingFlags bflags, bool ignoreCase, bool throwOnBindFailure)
271 throw new ArgumentNullException ("type");
274 throw new ArgumentNullException ("method");
276 if (!type.IsSubclassOf (typeof (MulticastDelegate)))
277 throw new ArgumentException ("type is not subclass of MulticastDelegate.");
279 MethodInfo invoke = type.GetMethod ("Invoke");
280 ParameterInfo [] delargs = invoke.GetParameters ();
281 Type[] delargtypes = new Type [delargs.Length];
283 for (int i=0; i<delargs.Length; i++)
284 delargtypes [i] = delargs [i].ParameterType;
287 * FIXME: we should check the caller has reflection permission
288 * or if it lives in the same assembly...
292 * since we need to walk the inheritance chain anyway to
293 * find private methods, adjust the bindingflags to ignore
296 BindingFlags flags = BindingFlags.ExactBinding |
297 BindingFlags.Public | BindingFlags.NonPublic |
298 BindingFlags.DeclaredOnly | bflags;
301 flags |= BindingFlags.IgnoreCase;
303 MethodInfo info = null;
305 for (Type targetType = target; targetType != null; targetType = targetType.BaseType) {
306 MethodInfo mi = targetType.GetMethod (method, flags,
307 null, delargtypes, new ParameterModifier [0]);
308 if (mi != null && return_type_match (invoke.ReturnType, mi.ReturnType)) {
315 if (throwOnBindFailure)
316 throw new ArgumentException ("Couldn't bind to method '" + method + "'.");
324 public static Delegate CreateDelegate (Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure)
327 throw new ArgumentNullException ("target");
329 MethodInfo info = GetCandidateMethod (type, target, method,
330 BindingFlags.Static, ignoreCase, throwOnBindFailure);
334 return CreateDelegate_internal (type, null, info, throwOnBindFailure);
337 public static Delegate CreateDelegate (Type type, Type target, string method) {
338 return CreateDelegate (type, target, method, false, true);
341 public static Delegate CreateDelegate (Type type, Type target, string method, bool ignoreCase) {
342 return CreateDelegate (type, target, method, ignoreCase, true);
345 public static Delegate CreateDelegate (Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure)
348 throw new ArgumentNullException ("target");
350 MethodInfo info = GetCandidateMethod (type, target.GetType (), method,
351 BindingFlags.Instance, ignoreCase, throwOnBindFailure);
355 return CreateDelegate_internal (type, target, info, throwOnBindFailure);
358 public static Delegate CreateDelegate (Type type, object target, string method, bool ignoreCase) {
359 return CreateDelegate (type, target, method, ignoreCase, true);
362 public object DynamicInvoke (params 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 (data.method_name, mtypes);
377 if ((m_target != null) && Method.IsStatic) {
378 // The delegate is bound to m_target
380 object[] newArgs = new object [args.Length + 1];
381 args.CopyTo (newArgs, 1);
382 newArgs [0] = m_target;
385 args = new object [] { m_target };
387 return Method.Invoke (null, args);
390 return Method.Invoke (m_target, args);
393 public virtual object Clone ()
395 return MemberwiseClone ();
398 public override bool Equals (object obj)
400 Delegate d = obj as Delegate;
405 // Do not compare method_ptr, since it can point to a trampoline
406 if (d.m_target == m_target && d.method == method) {
407 if (d.data != null || data != null) {
409 if (d.data != null && data != null)
410 return (d.data.target_type == data.target_type && d.data.method_name == data.method_name);
420 public override int GetHashCode ()
422 return method.GetHashCode () ^ (m_target != null ? m_target.GetHashCode () : 0);
425 protected virtual MethodInfo GetMethodImpl ()
430 // This is from ISerializable
431 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
433 DelegateSerializationHolder.GetDelegateData (this, info, context);
436 public virtual Delegate[] GetInvocationList()
438 return new Delegate[] { this };
442 /// Returns a new MulticastDelegate holding the
443 /// concatenated invocation lists of MulticastDelegates a and b
445 public static Delegate Combine (Delegate a, Delegate b)
455 if (a.GetType () != b.GetType ())
456 throw new ArgumentException (Locale.GetText ("Incompatible Delegate Types."));
458 return a.CombineImpl (b);
462 /// Returns a new MulticastDelegate holding the
463 /// concatenated invocation lists of an Array of MulticastDelegates
465 [System.Runtime.InteropServices.ComVisible (true)]
466 public static Delegate Combine (params 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 d1, Delegate d2)
511 if ((object)d1 == null) {
512 if ((object)d2 == null)
515 } else if ((object) d2 == null)
518 return d1.Equals (d2);
521 public static bool operator != (Delegate d1, Delegate d2)
526 internal bool IsTransparentProxy ()
528 return RemotingServices.IsTransparentProxy (m_target);