C# if else 异常

标签 c# reflection reflection.emit il system.reflection

我试图通过 System.Reflection 和 System.Reflection.Emit 使 if-else 在 IL 中工作。这是我目前拥有的代码:

Label inequality = new System.Reflection.Emit.Label();
Label equality = new System.Reflection.Emit.Label();
Label end = new System.Reflection.Emit.Label();
var method = new DynamicMethod("dummy", null, Type.EmptyTypes);
var g = method.GetILGenerator();
g.Emit(OpCodes.Ldstr, "string");
g.Emit(OpCodes.Ldstr, "string");
g.Emit(OpCodes.Call, typeof(String).GetMethod("op_Equality", new Type[]{typeof(string), typeof(string)}));
g.Emit(OpCodes.Ldc_I4, 0);
g.Emit(OpCodes.Ceq);
g.Emit(OpCodes.Brtrue_S, inequality);
g.MarkLabel(inequality); //HERE it throws exception
g.Emit(OpCodes.Ldstr, "Specified strings are different.");
g.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[]{typeof(string)}));
g.Emit(OpCodes.Br_S, end);
g.Emit(OpCodes.Brfalse_S, equality);
g.MarkLabel(equality);
g.Emit(OpCodes.Ldstr, "Specified strings are same.");
g.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
g.Emit(OpCodes.Br_S, end);
g.MarkLabel(end);
g.Emit(OpCodes.Ret);

var action = (Action)method.CreateDelegate(typeof(Action));
action();

Console.Read();

现在,在我标记标签的行上它抛出了这个异常:

对象引用未设置到对象的实例。

My exception.

但我认为这是愚蠢的,因为该标签与新的 Label 对象相关联。 有谁知道我该如何解决这个问题?谢谢。

最佳答案

在定义 g 之后,您不需要将标签定义为 Label whatever = g.DefineLabel(); 吗?

关于C# if else 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11139912/

相关文章:

c# - ASP MVC 工作流工具表单逻辑和权限

C# : How to pause the thread and continue when some event occur?

c# - 按降序排列学生

c# - 是否可以装饰事件处理程序来执行登录检查?

基于对象类型的 Java getter 返回类型

c# - Type.GetType(string typeName) 返回 null

java - 用反射覆盖注释?

c# - 从 TypeBuilder.CreateType 返回的类型的 Activator.CreateInstance 抛出 ArgumentException

.net - 程序集未正确保存

c# - PropertyAttributes.HasDefault 和 PropertyBuilder.SetConstant 的含义