如何使用 ILGenerator 为 ref 局部变量发出 IL?

问题描述 投票:0回答:1

以下 C# 代码片段:

int x = 10;
ref int y = ref x;

被编译成这个IL:

.locals init (
    [0] int32 x,
    [1] int32& y
)

ldc.i4.s 10
stloc.0
ldloca.s 0
stloc.1
ret

如何使用

int32&
创建类型为
ILGenerator
的本地?

我查看了

ILGenerator.DeclareLocal()
方法,但没有找到合适的重载。

c# .net clr cil
1个回答
0
投票

按引用局部变量只是不同类型的局部变量。要通过引用创建类型,您应该调用

.MakeByRefType()

        // void Foo()
        var meth = new DynamicMethod("Foo", returnType: typeof(void), parameterTypes: null);
        var il = meth.GetILGenerator();

        // int x;
        var xLocal = il.DeclareLocal(typeof(int));
        // ref int y;
        var yLocal = il.DeclareLocal(typeof(int).MakeByRefType());

        // x = 10;
        il.Emit(OpCodes.Ldc_I4, 10);
        il.Emit(OpCodes.Stloc, xLocal);

        // ref y = ref x;
        il.Emit(OpCodes.Ldloca, xLocal);
        il.Emit(OpCodes.Stloc, yLocal);

        il.Emit(OpCodes.Ret);

        var action = meth.CreateDelegate<Action>();
        action(); // ensure no InvalidProgramException
© www.soinside.com 2019 - 2024. All rights reserved.