Reflection.Emit throws BadImageFormatException

本文关键字:BadImageFormatException throws Emit Reflection | 更新日期: 2023-09-27 17:57:13

我试图在运行时生成一个新的类/对象。

在阅读了如何使用PropertyBuilder创建私有财产之后,我已经设法实现了每一个,一切都像我需要它一样。

但是一旦我试图实例化我的新对象,我就会收到BadImageFormatException

这似乎是一个类似的问题,但尚未解决 有没有办法检测系统.反射.发射?

这是我的代码:

田:

internal class Field {
      public string FieldName;
      public Type FieldType;
      public string Value;
    }

发电机代码:

var xx = new List<Field>(new[] { new Field { FieldName = "Name", FieldType = typeof(string), Value = "Hello World" },
        new Field { FieldName = "Id", FieldType = typeof(int), Value = "1" } });
      this.DoVodoo(xx);

魔术

private dynamic DoVodoo(IEnumerable<Field> fields) {
      var aName = new AssemblyName("DynamicAssemblyExample");
      var ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.RunAndSave);
      var mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");
      // Create class with all needed Properties
      var tb = mb.DefineType("ParamRow", TypeAttributes.Public, typeof(object));
      foreach (var field in fields) {
        var pb = tb.DefineProperty(field.FieldName, PropertyAttributes.None, CallingConventions.HasThis, field.FieldType, null);
        var getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
        // Define the "get" accessor method for the Property.
        var custNameGetPropMthdBldr = tb.DefineMethod($"get_{field.FieldName}", getSetAttr, typeof(string), Type.EmptyTypes);
        var custNameGetIL = custNameGetPropMthdBldr.GetILGenerator();
        custNameGetIL.Emit(OpCodes.Ldarg_0);
        custNameGetIL.Emit(OpCodes.Ldfld, custNameGetPropMthdBldr);
        custNameGetIL.Emit(OpCodes.Ret);
        // Define the "set" accessor method for CustomerName.
        var custNameSetPropMthdBldr = tb.DefineMethod($"set_{field.FieldName}", getSetAttr, null, new[] { typeof(string) });
        var custNameSetIL = custNameSetPropMthdBldr.GetILGenerator();
        custNameSetIL.Emit(OpCodes.Ldarg_0);
        custNameSetIL.Emit(OpCodes.Ldarg_1);
        //custNameSetIL.Emit(OpCodes.Stfld, custNameGetPropMthdBldr);
        custNameSetIL.Emit(OpCodes.Stfld, custNameSetPropMthdBldr);
        custNameSetIL.Emit(OpCodes.Ret);
        // Last, we must map the two methods created above to our PropertyBuilder to 
        // their corresponding behaviors, "get" and "set" respectively. 
        pb.SetGetMethod(custNameGetPropMthdBldr);
        pb.SetSetMethod(custNameSetPropMthdBldr);
      }
      var finalType = tb.CreateType();
      var result = new List<object>();
      foreach (var field in fields) {
        var inst = ab.CreateInstance(finalType.Name);
        finalType.GetProperty(field.FieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).SetValue(inst, field.Value); //<-- Here comes the trouble
        result.Add(inst);
      }
      return result;}

关于如何实例化我新创建的 ParamRow 型的任何帮助,我们非常感谢。

奖金问题:为什么会有BadImageFormatException

附加信息:

  • .网络框架 4.6.1
  • 编译器目标是 x86
  • 以前从未有过Reflection.Emit

Reflection.Emit throws BadImageFormatException

您得到的异常.Message是重要的位:

字段标记超出范围。

这告诉您它不了解要在ldfld/stfld中使用哪个字段 - 这是因为您正在向其传递方法令牌(custNameGetPropMthdBldr/custNameSetPropMthdBldr)而不是字段令牌。

您需要定义和使用字段:

var fb = tb.DefineField("__" + field.FieldName, field.FieldType, FieldAttributes.Private);
// ...
custNameGetIL.Emit(OpCodes.Ldarg_0);
custNameGetIL.Emit(OpCodes.Ldfld, fb);
custNameGetIL.Emit(OpCodes.Ret);
// ...
custNameSetIL.Emit(OpCodes.Ldarg_0);
custNameSetIL.Emit(OpCodes.Ldarg_1);
custNameSetIL.Emit(OpCodes.Stfld, fb);
custNameSetIL.Emit(OpCodes.Ret);

另请注意,通过反射创建对象时,使用 Type使用名称更有效;这工作正常:

var inst = Activator.CreateInstance(finalType);