microsoft/teams.net

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
releases/v2

Branches

Tags

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

Clone

HTTPS

Download ZIP

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

57lines · 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 var resultProperty = task.GetType().GetProperty("Result");
24 if (resultProperty is not null && task.GetType().IsGenericType)
25 {
26 return resultProperty.GetValue(task);
27 }
28 return null;
29 }
30
31 return res;
32 }
33
34 public static Delegate CreateDelegate(this MethodInfo methodInfo, object target)
35 {
36 Func<Type[], Type> getType;
37 var isAction = methodInfo.ReturnType.Equals(typeof(void));
38 var types = methodInfo.GetParameters().Select(p => p.ParameterType);
39
40 if (isAction)
41 {
42 getType = Expression.GetActionType;
43 }
44 else
45 {
46 getType = Expression.GetFuncType;
47 types = types.Concat([methodInfo.ReturnType]);
48 }
49
50 if (methodInfo.IsStatic)
51 {
52 return Delegate.CreateDelegate(getType(types.ToArray()), methodInfo);
53 }
54
55 return Delegate.CreateDelegate(getType(types.ToArray()), target, methodInfo.Name);
56 }
57}