1 // -----------------------------------------------------------------------
\r
2 // Copyright (c) Microsoft Corporation. All rights reserved.
\r
3 // -----------------------------------------------------------------------
\r
5 using System.Diagnostics.CodeAnalysis;
\r
6 using System.Reflection;
\r
7 using Microsoft.Internal;
\r
9 namespace System.ComponentModel.Composition.Primitives
\r
11 [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
\r
12 public class ExportedDelegate
\r
14 private object _instance;
\r
15 private MethodInfo _method;
\r
17 protected ExportedDelegate() { }
\r
19 [System.Security.SecurityCritical]
\r
21 public ExportedDelegate(object instance, MethodInfo method)
\r
23 Requires.NotNull(method, "method");
\r
25 this._instance = instance;
\r
26 this._method = method;
\r
29 public virtual Delegate CreateDelegate(Type delegateType)
\r
31 Requires.NotNull(delegateType, "delegateType");
\r
33 if (delegateType == typeof(Delegate) || delegateType == typeof(MulticastDelegate))
\r
35 Type funcOrAction = ConvertMethodInfoToFuncOrActionType(this._method);
\r
37 if (funcOrAction != null)
\r
39 delegateType = funcOrAction;
\r
47 return Delegate.CreateDelegate(delegateType, this._instance, this._method, false);
\r
50 private static Type[] _funcTypes =
\r
52 typeof(Func<>), typeof(Func<,>), typeof(Func<,,>), typeof(Func<,,,>), typeof(Func<,,,,>)
\r
53 #if CLR40 && !SILVERLIGHT
\r
54 , typeof(Func<,,,,,>), typeof(Func<,,,,,,>), typeof(Func<,,,,,,,>), typeof(Func<,,,,,,,,>)
\r
58 private static Type[] _actionTypes =
\r
60 typeof(Action), typeof(Action<>), typeof(Action<,>), typeof(Action<,,>), typeof(Action<,,,>)
\r
61 #if CLR40 && !SILVERLIGHT
\r
62 , typeof(Action<,,,,>), typeof(Action<,,,,,>), typeof(Action<,,,,,,>), typeof(Action<,,,,,,,>)
\r
66 private static Type ConvertMethodInfoToFuncOrActionType(MethodInfo method)
\r
68 ParameterInfo[] parameters = method.GetParameters();
\r
70 bool isVoid = method.ReturnType == typeof(void);
\r
71 Type[] typeArray = isVoid ? _actionTypes : _funcTypes;
\r
73 if (parameters.Length >= typeArray.Length)
\r
78 Type[] genericArgTypes = new Type[parameters.Length + (isVoid ? 0 : 1)];
\r
80 for (int i = 0; i < parameters.Length; i++)
\r
82 genericArgTypes[i] = parameters[i].ParameterType;
\r
87 genericArgTypes[parameters.Length] = method.ReturnType;
\r
90 Type delegateType = typeArray[parameters.Length].IsGenericType ?
\r
91 typeArray[parameters.Length].MakeGenericType(genericArgTypes) :
\r
92 typeArray[parameters.Length];
\r
94 return delegateType;
\r