发出局部变量并为其分配值 [英] 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;
推荐答案
使用 Ldloc
和 Stloc
操作码以读取和写入局部变量:
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(OpCodes.Ldc_I4, 6); // Store "6" ...
ilGen.Emit(OpCodes.Stloc, b); // ... in "b".
ilGen.Emit(OpCodes.Ldloc, a); // Load "a" ...
ilGen.Emit(OpCodes.Ldloc, b); // ... and "b".
ilGen.Emit(OpCodes.Add); // Sum them ...
ilGen.Emit(OpCodes.Ret); // ... and return the result.
请注意,C#编译器使用某些操作码的简写形式(通过.NET Reflector):
Note that the C# compiler uses the shorthand form of some of the opcodes (via .NET Reflector):
.locals init (
[0] int32 a,
[1] int32 b)
ldc.i4.5
stloc.0
ldc.i4.6
stloc.1
ldloc.0
ldloc.1
add
ret
这篇关于发出局部变量并为其分配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文