动态模块不支持调用的成员

时间:2017-09-25 00:32:58

标签: c# reflection.emit

运行此代码时出现错误:

  var asmName = new AssemblyName("DynamicAssembly");
  var asmBuilder = AssemblyBuilder.DefineDynamicAssembly
      (asmName, AssemblyBuilderAccess.Run);
  var moduleBuilder = asmBuilder.DefineDynamicModule("DynamicModule");
  var typeBuilder = moduleBuilder.DefineType("DynamicType", TypeAttributes.Public);
  var methodBuilder = typeBuilder.DefineMethod("DynamicMethod", MethodAttributes.Static, typeof(double), new[] { typeof(double), typeof(double), typeof(double) });
  myexp.Lambda.CompileToMethod(methodBuilder);
  asmBuilder.SetEntryPoint(methodBuilder);

  MethodInfo barMethod = asmBuilder.EntryPoint;
  result = barMethod.Invoke(null, new object[] { 50d, 1d, 3d });

我在最后一行得到错误

  

动态模块不支持调用的成员。

我只是想调用这个方法。

我添加了

  <runtime>
    <loadFromRemoteSources enabled="true"/>
  </runtime>

到我的app.config无济于事。

1 个答案:

答案 0 :(得分:3)

正如@thehennyy在评论中指出的那样,你应该在调用方法之前调用typeBuilder.CreateType(),但是从Invoke调用methodBuilder会导致同样的错误。

我设法从创建的类型中获取它之后调用方法:

var type = typeBuilder.CreateType();
var method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic);

以下是我使用的完整代码:

Expression<Func<double, double, double, double>> myexp = (a, b, c) => a * b * c;
var methodName = "DynamicMethod";

var asmName = new AssemblyName("DynamicAssembly");
var asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
var moduleBuilder = asmBuilder.DefineDynamicModule("DynamicModule");
var typeBuilder = moduleBuilder.DefineType("DynamicType", TypeAttributes.Public);
var methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Static, typeof(double), new[] { typeof(double), typeof(double), typeof(double) });

myexp.CompileToMethod(methodBuilder);
var type = typeBuilder.CreateType();
var method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic);

asmBuilder.SetEntryPoint(method);
MethodInfo barMethod = asmBuilder.EntryPoint;
var result = barMethod.Invoke(null, new object[] { 50d, 1d, 3d });