-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathMethodOf.cs
70 lines (61 loc) · 2.57 KB
/
MethodOf.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
61
62
63
64
65
66
67
68
69
70
using System;
using System.Linq.Expressions;
using System.Reflection;
using HarmonyLib;
namespace Multiplayer.Client.Util;
public static class MethodOf
{
/// <summary>Given a lambda expression that calls a method, returns the method info</summary>
/// <param name="expression">The lambda expression using the method</param>
/// <returns>The method in the lambda expression</returns>
///
public static MethodInfo Inner(Expression<Action> expression)
{
return Inner((LambdaExpression)expression);
}
/// <summary>Given a lambda expression that calls a method, returns the method info</summary>
/// <typeparam name="T">The generic type</typeparam>
/// <param name="expression">The lambda expression using the method</param>
/// <returns>The method in the lambda expression</returns>
///
public static MethodInfo Inner<T>(Expression<Action<T>> expression)
{
return Inner((LambdaExpression)expression);
}
/// <summary>Given a lambda expression that calls a method, returns the method info</summary>
/// <typeparam name="T">The generic type</typeparam>
/// <typeparam name="TResult">The generic result type</typeparam>
/// <param name="expression">The lambda expression using the method</param>
/// <returns>The method in the lambda expression</returns>
///
public static MethodInfo Inner<T, TResult>(Expression<Func<T, TResult>> expression)
{
return Inner((LambdaExpression)expression);
}
/// <summary>Given a lambda expression that calls a method, returns the method info</summary>
/// <param name="expression">The lambda expression using the method</param>
/// <returns>The method in the lambda expression</returns>
///
public static MethodInfo Inner(LambdaExpression expression)
{
if (expression.Body is not MethodCallExpression outermostExpression)
{
if (expression.Body is UnaryExpression { Operand: MethodCallExpression me } ue &&
me.Object is ConstantExpression ce && ce.Value is MethodInfo mi)
return mi;
throw new ArgumentException("Invalid Expression. Expression should consist of a Method call only.");
}
var method = outermostExpression.Method;
if (method is null)
throw new Exception($"Cannot find method for expression {expression}");
return method;
}
public static MethodInfo Lambda(Delegate del)
{
return del.Method;
}
public static HarmonyMethod Harmony(this MethodInfo m)
{
return new HarmonyMethod(m);
}
}