C#if else例外

时间:2012-06-21 14:02:15

标签: 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对象相关联。 有谁知道我该如何解决这个问题?感谢。

1 个答案:

答案 0 :(得分:7)

定义Label whatever = g.DefineLabel();后,您是否需要将标签定义为g