2012-06-21 14 views
5

Sto cercando di rendere if-else che funziona in IL tramite System.Reflection e System.Reflection.Emit. Questo è il codice che ho attualmente:C# in caso di eccezione

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

Ora, sulla linea dove sto marcatura etichetta che mi genera questa eccezione:

riferimento oggetto non impostato a un'istanza di un oggetto.

My exception.

Ma penso che sia la stupidità, perché questa etichetta è associata a nuovo oggetto Label. Qualcuno sa come posso risolvere questo problema? Grazie.

risposta

7

Non è necessario definire le etichette come Label whatever = g.DefineLabel(); dopo aver definito g?

+0

oh sì, è vero. Grazie. – user35443