Do int ref parameter get boxed?

后端 未结 6 1917
-上瘾入骨i
-上瘾入骨i 2021-02-12 13:14

Say I have the following code:

void Main()
{
    int a = 5;
    f1(ref a);
}

public void f1(ref int a)
{
    if(a > 7) return;
    a++;
    f1(ref a);
    Co         


        
6条回答
  •  无人及你
    2021-02-12 13:22

    Your Console.WriteLine(a); will be executed after recursion is finished. Recursion is finished when value of int becomes 8. And to make it to 8 it has recursion for 3 times. So, after last it will print 8 and then pass control to recursion above which will print 8 again as variable referred has value became 8.

    Also check ILDASM output

    .method public hidebysig static void  f1(int32& a) cil managed
    {
      // Code size       26 (0x1a)
      .maxstack  8
      IL_0000:  ldarg.0
      IL_0001:  ldind.i4
      IL_0002:  ldc.i4.7
      IL_0003:  ble.s      IL_0006
      IL_0005:  ret
      IL_0006:  ldarg.0
      **IL_0007:  dup**
      IL_0008:  ldind.i4
      IL_0009:  ldc.i4.1
      IL_000a:  add
      IL_000b:  stind.i4
      IL_000c:  ldarg.0
      IL_000d:  call       void ConsoleApplication1.Program::f1(int32&)
      IL_0012:  ldarg.0
      IL_0013:  ldind.i4
      IL_0014:  call       void [mscorlib]System.Console::WriteLine(int32)
      IL_0019:  ret
    } // end of method Program::f1
    

提交回复
热议问题