我尝试创建一个委托来调用静态泛型方法。但我得到了错误:检测到无效代码!有人知道我的 IL 有什么问题吗?
示例代码中的 FindStaticMethod 调用正在工作并返回带有给定类型参数的方法信息!
public delegate object GenericStaticInvoker(params object[] arguments);
public static GenericStaticInvoker GenericMethodInvokerStaticMethod(Type type, string methodName, Type[] typeArguments, Type[] parameterTypes)
{
MethodInfo methodInfo;
ParameterInfo[] parameters;
// find the method to be invoked
FindStaticMethod(type, methodName, typeArguments, parameterTypes, out methodInfo, out parameters);
string name = string.Format("__MethodInvoker_{0}_ON_{1}", methodInfo.Name, methodInfo.DeclaringType.Name);
DynamicMethod dynamicMethod;
dynamicMethod = new DynamicMethod(name, typeof(object), new Type[] { typeof(object[]) }, methodInfo.DeclaringType);
ILGenerator generator = dynamicMethod.GetILGenerator();
// define local vars
if (methodInfo.ReturnType != typeof(void))
generator.DeclareLocal(methodInfo.ReturnType);
for (int i = 0; i < parameters.Length; i++)
{
// load paramters they are passed as an object array
generator.Emit(OpCodes.Ldarg_1);
// load array element
generator.Emit(OpCodes.Ldc_I4, i);
generator.Emit(OpCodes.Ldelem_Ref);
// cast or unbox parameter as needed
Type parameterType = parameters[i].ParameterType;
if (parameterType.IsClass)
{
generator.Emit(OpCodes.Castclass, parameterType);
}
else
{
generator.Emit(OpCodes.Unbox_Any, parameterType);
}
}
// call method
generator.EmitCall(OpCodes.Call, methodInfo, null);
// handle method return if needed
if (methodInfo.ReturnType == typeof(void))
{
// return null
generator.Emit(OpCodes.Ldnull);
generator.Emit(OpCodes.Ret);
}
else
{
// box value if needed
if (methodInfo.ReturnType.IsValueType)
{
generator.Emit(OpCodes.Box, methodInfo.ReturnType);
}
// store to the local var
generator.Emit(OpCodes.Stloc_0);
// load local and return
generator.Emit(OpCodes.Ldloc_0);
generator.Emit(OpCodes.Ret);
}
// return delegate
return (GenericStaticInvoker)dynamicMethod.CreateDelegate(typeof(GenericStaticInvoker));
}