2012-06-21 52 views
5

Estoy tratando de hacer if-else trabajando en IL por System.Reflection y System.Reflection.Emit. Este es el código que tengo actualmente:C# if else excepción

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(); 

Ahora, en la línea donde estoy etiqueta de señalización que me lanza esta excepción:

referencia a objeto no establecida como instancia de un objeto.

My exception.

Pero creo que es la estupidez, porque esa etiqueta se asocia con el nuevo objeto etiqueta. ¿Alguien sabe cómo puedo resolver este problema? Gracias.

Respuesta

7

¿No necesita definir sus etiquetas como Label whatever = g.DefineLabel(); después de haber definido g?

+0

oh sí, eso es verdad. Gracias. – user35443