嵌套 'fixed' 语句

Nested 'fixed' statement

根据 C# reference for fixed 声明:

The fixed statement prevents the garbage collector from relocating a movable variable. ... After the code in the statement is executed, any pinned variables are unpinned and subject to garbage collection. Therefore, do not point to those variables outside the fixed statement.

我在此页面上未找到的内容:如果我们为同一变量嵌套 fixed 语句会怎样?

var data = new byte[100];
unsafe
{
    fixed(byte* pData = data)
    {
        //pData points to the "pinned" variable
        fixed(byte* pData2 = data)
        {
            //pData points to the "pinned" variable
            //pData2 points to the "pinned" variable
        }
        //Does pData still point to the "pinned" variable?
    }
}

上面的代码当然只是为了说明。实际使用可以是递归函数。

这就像您期望的那样工作,必然如此。 fixed 属性 与指针变量关联,而不是它固定的对象。所以在内部作用域块中有两个固定数组的变量。下一个是一个固定它的变量。它仍然被固定。

当你递归时,数组是在方法之外声明的,那么会有更多的变量固定它。

体面的心理形象是根据 fixed 为对象初始化 GCHandle 的假设工作的。您可以为一个对象创建尽可能多的 GCHandle,GC 不会介意。这实际上不会在运行时发生,fixed 比 GCHandle 更有效。它是变量的一个属性,在像 ildasm.exe 这样的反汇编程序中显示为 [固定]。 GC 在遍历堆栈时发现属性,查找对象引用。