-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
ExportedDelegate.cs
60 lines (50 loc) · 1.88 KB
/
ExportedDelegate.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.Primitives
{
public class ExportedDelegate
{
private readonly object? _instance;
private readonly MethodInfo _method = null!;
protected ExportedDelegate() { }
public ExportedDelegate(object? instance, MethodInfo method)
{
Requires.NotNull(method, nameof(method));
_instance = instance;
_method = method;
}
public virtual Delegate? CreateDelegate(Type delegateType)
{
Requires.NotNull(delegateType, nameof(delegateType));
if (delegateType == typeof(Delegate) || delegateType == typeof(MulticastDelegate))
{
delegateType = CreateStandardDelegateType();
}
try
{
return _method.CreateDelegate(delegateType, _instance);
}
catch (ArgumentException)
{
//Bind failure occurs return null;
return null;
}
}
private Type CreateStandardDelegateType()
{
ParameterInfo[] parameters = _method.GetParameters();
// This array should contains a lit of all argument types, and the last one is the return type (could be void)
Type[] parameterTypes = new Type[parameters.Length + 1];
parameterTypes[parameters.Length] = _method.ReturnType;
for (int i = 0; i < parameters.Length; i++)
{
parameterTypes[i] = parameters[i].ParameterType;
}
return Expression.GetDelegateType(parameterTypes);
}
}
}