microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
Libraries/Microsoft.Teams.Common/Extensions/MethodInfoExtensions.cs
49lines · modecode
| 1 | using System.Linq.Expressions; |
| 2 | using System.Reflection; |
| 3 | |
| 4 | namespace Microsoft.Teams.Common.Extensions; |
| 5 | |
| 6 | public static class MethodInfoExtensions |
| 7 | { |
| 8 | public static async Task<object?> InvokeAsync(this MethodInfo methodinfo, object? target, object?[]? args) |
| 9 | { |
| 10 | var res = methodinfo.Invoke(target, args); |
| 11 | |
| 12 | if (res is Task<object?> taskWithValue) |
| 13 | { |
| 14 | return await taskWithValue.ConfigureAwait(false); |
| 15 | } |
| 16 | |
| 17 | if (res is Task task) |
| 18 | { |
| 19 | await task.ConfigureAwait(false); |
| 20 | return null; |
| 21 | } |
| 22 | |
| 23 | return res; |
| 24 | } |
| 25 | |
| 26 | public static Delegate CreateDelegate(this MethodInfo methodInfo, object target) |
| 27 | { |
| 28 | Func<Type[], Type> getType; |
| 29 | var isAction = methodInfo.ReturnType.Equals(typeof(void)); |
| 30 | var types = methodInfo.GetParameters().Select(p => p.ParameterType); |
| 31 | |
| 32 | if (isAction) |
| 33 | { |
| 34 | getType = Expression.GetActionType; |
| 35 | } |
| 36 | else |
| 37 | { |
| 38 | getType = Expression.GetFuncType; |
| 39 | types = types.Concat([methodInfo.ReturnType]); |
| 40 | } |
| 41 | |
| 42 | if (methodInfo.IsStatic) |
| 43 | { |
| 44 | return Delegate.CreateDelegate(getType(types.ToArray()), methodInfo); |
| 45 | } |
| 46 | |
| 47 | return Delegate.CreateDelegate(getType(types.ToArray()), target, methodInfo.Name); |
| 48 | } |
| 49 | } |