microsoft/teams.net

Public

mirrored fromhttps://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
436972edd2a63f773497d45cdc1de6342c7a1c20

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

Libraries/Microsoft.Teams.Common/Extensions/MethodInfoExtensions.cs

52lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License.
3
4using System.Linq.Expressions;
5using System.Reflection;
6
7namespace Microsoft.Teams.Common.Extensions;
8
9public static class MethodInfoExtensions
10{
11 public static async Task<object?> InvokeAsync(this MethodInfo methodInfo, object? target, object?[]? args)
12 {
13 var res = methodInfo.Invoke(target, args);
14
15 if (res is Task<object?> taskWithValue)
16 {
17 return await taskWithValue.ConfigureAwait(false);
18 }
19
20 if (res is Task task)
21 {
22 await task.ConfigureAwait(false);
23 return task.GetType().GetProperty("Result")?.GetValue(task);
24 }
25
26 return res;
27 }
28
29 public static Delegate CreateDelegate(this MethodInfo methodInfo, object target)
30 {
31 Func<Type[], Type> getType;
32 var isAction = methodInfo.ReturnType.Equals(typeof(void));
33 var types = methodInfo.GetParameters().Select(p => p.ParameterType);
34
35 if (isAction)
36 {
37 getType = Expression.GetActionType;
38 }
39 else
40 {
41 getType = Expression.GetFuncType;
42 types = types.Concat([methodInfo.ReturnType]);
43 }
44
45 if (methodInfo.IsStatic)
46 {
47 return Delegate.CreateDelegate(getType(types.ToArray()), methodInfo);
48 }
49
50 return Delegate.CreateDelegate(getType(types.ToArray()), target, methodInfo.Name);
51 }
52}