C# &引用;调用的目标已引发异常;使用两个参数实现函数时出现问题

C# &引用;调用的目标已引发异常;使用两个参数实现函数时出现问题,c#,lambda,reflection.emit,C#,Lambda,Reflection.emit,我正在尝试为动态生成的类/方法实现接口。对于带有一个参数(在代码中注释)的方法,实现是可以的。但当方法有两个或多个参数时,它会抛出“异常已被调用的目标抛出”。 无法找出两个参数的错误所在?任何帮助都将不胜感激。 下面是我的代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expre

我正在尝试为动态生成的类/方法实现接口。对于带有一个参数(在代码中注释)的方法,实现是可以的。但当方法有两个或多个参数时,它会抛出“异常已被调用的目标抛出”。 无法找出两个参数的错误所在?任何帮助都将不胜感激。 下面是我的代码:

using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Net.Http;
    using System.Reflection;
    using System.Reflection.Emit;
    using System.Security.Permissions;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Web.Http;
    using System.Web.Http.Controllers;

    namespace ConsoleApplication7
    {
        public class Foo
        {
            public string Bar(string m)
            {
                return m;
            }

        }
        public interface IFoo
        {
            string Barz(int i, int s);
            //string Barz(int i);// works good
        }

        public class Program
        {

            public string my(int w, int s)
            {
                return (s + w).ToString();
            }
            [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
            public void TestMethod()
            {

                var ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("TestAssembly"), AssemblyBuilderAccess.RunAndSave);

                var mb = ab.DefineDynamicModule("Test");
                var tb = mb.DefineType("Foo", typeof(Foo).Attributes, typeof(Foo));
                tb.AddInterfaceImplementation(typeof(IFoo));
                foreach (var imethod in typeof(IFoo).GetMethods())
                {
                    var method =
                      tb.DefineMethod
                      (
                        "@@" + imethod.Name,
                        MethodAttributes.Private | MethodAttributes.Static,
                        CallingConventions.Standard,
                        imethod.ReturnType,
                        imethod.GetParameters().Select(n => n.ParameterType).ToArray()
                      );

                    var thisParameter = Expression.Parameter(typeof(IFoo), "this");
                    var param = new ParameterExpression[] { Expression.Parameter(typeof(int)), Expression.Parameter(typeof(int)) };

                    var bodyExpression =
                      Expression.Lambda<Func<int,int, string>>(
                      Expression.Call(
                         Expression.New(typeof(Program)),
                         typeof(Program).GetMethod("my", new Type[] { typeof(int), typeof(int) }), param

                         ), param);
                    //var y = bodyExpression.Compile();//compiles good
                    //  var p = y.Invoke(200, "");//invocation is ok
                    bodyExpression.CompileToMethod(method);
                    var mp = imethod.GetParameters().Select(r => r.ParameterType).ToArray();
                    var stub =
                      tb.DefineMethod(imethod.Name, MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.Standard,
                       imethod.ReturnType, mp);
                    var il = stub.GetILGenerator();
                    il.Emit(OpCodes.Ldarg_0);
                    il.EmitCall(OpCodes.Call, method, null);
                    il.Emit(OpCodes.Ret);
                    tb.DefineMethodOverride(stub, imethod);
                }
                var type = tb.CreateType();
                ab.Save("test.dll");
                var obj = CreateAndInvoke(type, null, "Barz", null);

                Console.ReadLine();

            }
            public static object CreateAndInvoke(Type typeName, object[] constructorArgs, string methodName, object[] methodArgs)
            {
                Type type = typeName;
                object instance = Activator.CreateInstance(type);
                object[] a = new object[] { 900 ,0};
                MethodInfo method = type.GetMethod(methodName);
                return method.Invoke(instance, a);//issue over here
            }
            [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
            public static void Main(string[] args)
            {
                new Program().TestMethod(); 

            }


        }
    }
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用System.Linq;
使用System.Linq.Expressions;
使用System.Net.Http;
运用系统反思;
使用System.Reflection.Emit;
使用System.Security.Permissions;
使用系统文本;
使用系统线程;
使用System.Threading.Tasks;
使用System.Web.Http;
使用System.Web.Http.Controller;
命名空间控制台应用程序7
{
公开课Foo
{
公共字符串栏(字符串m)
{
返回m;
}
}
公共接口IFoo
{
字符串Barz(int i,int s);
//stringbarz(inti);//工作正常
}
公共课程
{
公共字符串my(int w,int s)
{
return(s+w).ToString();
}
[PermissionSetAttribute(SecurityAction.Demand,Name=“FullTrust”)]
公共void TestMethod()
{
var ab=AssemblyBuilder.DefinedDynamicAssembly(新的AssemblyName(“TestAssembly”),AssemblyBuilderAccess.RunAndSave);
var mb=ab.DefinedDynamicModule(“测试”);
var tb=mb.DefineType(“Foo”,typeof(Foo.Attributes,typeof(Foo));
tb.AddInterfaceImplementation(类型化(IFoo));
foreach(typeof(IFoo.GetMethods())中的var-imethod)
{
var方法=
定义方法
(
“@@”+i方法名称,
MethodAttributes.Private | MethodAttributes.Static,
呼叫约定。标准,
i方法返回类型,
imethod.GetParameters().Select(n=>n.ParameterType).ToArray()
);
var thisparmeter=Expression.Parameter(typeof(IFoo),“this”);
var param=新参数Expression[]{Expression.Parameter(typeof(int)),Expression.Parameter(typeof(int))};
变量体表达式=
Lambda(
表情,打电话(
Expression.New(typeof(Program)),
typeof(Program).GetMethod(“my”,新类型[]{typeof(int),typeof(int)}),参数
),param);
//var y=bodyExpression.Compile();//编译良好
//var p=y.Invoke(200,“”;//调用正常
bodyExpression.CompileToMethod(方法);
var mp=imethod.GetParameters().Select(r=>r.ParameterType.ToArray();
var存根=
tb.DefineMethod(imethod.Name,MethodAttributes.Public | MethodAttributes.Virtual,CallingConventions.Standard,
i方法返回类型,mp);
var il=stub.GetILGenerator();
il.Emit(操作码.Ldarg_0);
EmitCall(操作码.Call,方法,null);
发射(操作码Ret);
tb.定义方法(存根,i方法);
}
var type=tb.CreateType();
ab.Save(“test.dll”);
var obj=CreateAndInvoke(类型,null,“Barz”,null);
Console.ReadLine();
}
公共静态对象CreateAndInvoke(类型typeName,对象[]构造函数Args,字符串methodName,对象[]methodArgs)
{
类型=类型名;
对象实例=Activator.CreateInstance(类型);
object[]a=新对象[]{900,0};
MethodInfo method=type.GetMethod(methodName);
return方法.Invoke(instance,a);//此处的问题
}
[PermissionSetAttribute(SecurityAction.Demand,Name=“FullTrust”)]
公共静态void Main(字符串[]args)
{
新程序().TestMethod();
}
}
}
无法找出两个参数的错误所在?任何帮助都将不胜感激

生成代码的代码没有任何意义。它的编写目的是为任意方法调用生成存根,然后将单个参数传递给该方法,而不管该方法的算术性如何。这是完全错误的;该代码仅适用于一个参数的方法


运行时将在验证或jitting期间识别该问题,并给出无效的程序异常,而不是运行堆栈并使其对齐。

该异常始终有一个您需要查看的内部异常。这一个描述了实际原因。@joey{“公共语言运行时检测到一个无效的程序。”}这是内部异常..无法理解这意味着什么您的程序生成另一个程序并运行它。生成的程序是无效的程序。修复代码生成器,使其生成合法代码。@ericlippert当函数有一个参数时,程序运行良好。这是一个编译器错误..还是传递给函数的参数太多?我看到一个。它需要两个。提供两个。我添加了il.Emit(操作码.Ldarg_1);现在,它的作用就像魅力一样