Emit local variable and assign a value to it
问题 I'm initializing an integer variable like this: LocalBuilder a = ilGen.DeclareLocal(typeof(Int32)); How can I access it and assign a value to it? I want to do something like this: int a, b; a = 5; b = 6; return a + b; 回答1: Use the Ldloc and Stloc opcodes to read and write local variables: LocalBuilder a = ilGen.DeclareLocal(typeof(Int32)); LocalBuilder b = ilGen.DeclareLocal(typeof(Int32)); ilGen.Emit(OpCodes.Ldc_I4, 5); // Store "5" ... ilGen.Emit(OpCodes.Stloc, a); // ... in "a". ilGen.Emit