Created
February 7, 2023 13:08
-
-
Save gustavopsantos/7a1b0c21e675bb063724f5a2e36679da to your computer and use it in GitHub Desktop.
InjectedMethodInfo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal sealed class InjectedMethodInfo | |
{ | |
public readonly MethodInfo MethodInfo; | |
public readonly ParameterInfo[] Parameters; | |
public readonly Action<object, object[]> Call; | |
public InjectedMethodInfo(MethodInfo methodInfo) | |
{ | |
MethodInfo = methodInfo; | |
Parameters = methodInfo.GetParameters(); | |
Call = GenerateCall(methodInfo); | |
} | |
private static Action<object, object[]> GenerateCall(MethodInfo methodInfo) | |
{ | |
var instance = Expression.Parameter(typeof(object), "instance"); | |
var arguments = Expression.Parameter(typeof(object[]), "arguments"); | |
var instanceCast = Expression.Convert(instance, methodInfo.DeclaringType!); | |
var methodParams = methodInfo.GetParameters(); | |
var argumentExpressions = new Expression[methodParams.Length]; | |
for (int i = 0; i < methodParams.Length; i++) | |
{ | |
var index = Expression.ArrayIndex(arguments, Expression.Constant(i)); | |
argumentExpressions[i] = Expression.Convert(index, methodParams[i].ParameterType); | |
} | |
var callExpression = (Expression) Expression.Call(instanceCast, methodInfo, argumentExpressions); | |
var expression = Expression.Lambda<Action<object, object[]>>(callExpression, instance, arguments); | |
return expression.Compile(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment