比其他局部变量更局部的变量(它真的是 "more local" 还是只是 "isolated" 其余的 "as local as" 是?)

Variables more local than the rest of local variables ( is it really "more local" or just "isolated" from the rest that are "as local as" it's?)

我有一个非常小而直接的问题,我想得到一个肯定的答案,并提前谢谢你们:

在一个方法(例如 main )中,我可以为代码的任何部分添加大括号 {} 以将某些行作为局部变量。

这是我的例子:

public static void Main (string[] args)
{
int a = 1;

{ int b = 2;
Console.WriteLine(b); 
}

Console.WriteLine(a);


}

变量"int b"在花括号的外面显然是不可访问的,现在我的问题是这个变量的内存位置,它会不会和main方法在同一个栈帧中在同一个内存堆栈中,或者它将被保存在主方法堆栈顶部的一个更新的堆栈帧中(就像被调用方法的参数和另一个方法中的局部变量)?

我认为区分 lifetimescope 会很有用:

Lifetime and scope are often confused because of the strong connection between the lifetime and scope of a local variable. The most succinct way to put it is that the contents of a local variable are guaranteed to be alive at least as long as the current "point of execution" is inside the scope of the local variable. "At least as long" of course implies "or longer"; capturing a local variable, for example, extends its lifetime

看看source

另外,根据这个answer并对其进行评论:

It is very much an implementation detail of the JIT compiler.

C# 代码被翻译成 IL 代码并且

IL works with an operation stack, but this does not directly correspond to a 'call stack'

看起来它依赖于实现。

不,大括号不充当堆栈框架b 也是 main 方法的自动变量,将被视为与 a 相同但有额外的范围界定 因此,它将与 main 方法在同一个内存堆栈中的同一个堆栈帧中。