【发布时间】:2019-03-21 11:19:50
【问题描述】:
我有一个类似下面代码的类:
public class MyClass
{
public int MyProperty1 { get; set; }
}
我希望创建一个动态方法调用tostring
public static string MyProperty1ToString(MyClass o){
return o.MyProperty1.ToString();
}
IL
MyProperty1ToString:
IL_0000: nop
IL_0001: ldarg.0
IL_0002: callvirt UserQuery+MyClass.get_MyProperty1
IL_0007: stloc.0
IL_0008: ldloca.s 00
IL_000A: call System.Int32.ToString
IL_000F: stloc.1
IL_0010: br.s IL_0012
IL_0012: ldloc.1
IL_0013: ret
所以我尝试使用 Emit 创建方法,但得到错误
InvalidProgramException : 公共语言运行时检测到无效程序
public class Program
{
public static void Main()
{
var obj = new MyClass() { MyProperty1 = 123 };
var prop = obj.GetType().GetProperty("MyProperty1");
var func = GetByPropertyCallToStringFunction<MyClass>(prop);
var data = func(obj); //InvalidProgramException : common language runtime detected an invalid program
}
public static Func<T, string> GetByPropertyCallToStringFunction<T>(PropertyInfo prop)
{
var type = prop.DeclaringType;
var propGetMethod = prop.GetMethod;
var propType = prop.PropertyType;
DynamicMethod dynamicMethod = new DynamicMethod($"{prop.Name}_method", typeof(string), new Type[] { type }, type.Module);
var toStringMethod = propType.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(p => p.Name == "ToString").First();
ILGenerator il = dynamicMethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, propGetMethod);
il.Emit(OpCodes.Stloc);
il.Emit(OpCodes.Ldloca_S, 00);
il.Emit(OpCodes.Call, toStringMethod);
il.Emit(OpCodes.Stloc_1);
il.Emit(OpCodes.Br_S, "IL_0012");
il.Emit(OpCodes.Ldloc_1);
il.Emit(OpCodes.Ret);
var invoke = (Func<T, string>)dynamicMethod.CreateDelegate(typeof(Func<T, string>));
return invoke;
}
}
问题
如何获得发出运行时编译器详细信息的错误消息?
我不知道什么时候只有InvalidProgramException
测试链接:C# Emit to create dynamic Property ToString method | C# Online Compiler | .NET Fiddle
【问题讨论】:
-
Br_S的参数应该是il.MarkLabel定义的标签。我假设你得到了错误,因为它不知道IL_0012的意思;即使是这样,反汇编的(Linqpad?)IL 代码示例和您的 Emit 代码之间的偏移无论如何都不会匹配,因为您省略了 Nop 指令。 -
我已经在这里解决了这个问题,但仅此一项并不能解决问题。
-
是的,这是 linqpad,谢谢@ckuri