简体   繁体   English

C#中的固定语句

[英]Fixed Statement in C#

We have similar code to the following in one of our projects. 在我们的一个项目中,我们有类似的代码。 Can anyone explain (in simple English) why the fixed statement is needed here? 任何人都可以解释(简单英语)为什么需要修复语句?

class TestClass
{
    int iMyVariable;
    static void Main()
    {
        TestClass oTestClass = new TestClass();
        unsafe
        {
            fixed (int* p = &oTestClasst.iMyVariable)
            {
                *p = 9;
            }
        }
    }
}

It fixes the pointer in memory. 它将指针固定在内存中。 Garbage collected languages have the freedom to move objects around memory for efficiency. 垃圾收集语言可以自由地在内存周围移动对象以提高效率。 This is all transparent to the programmer because they don't really use pointers in "normal" CLR code. 这对程序员来说都是透明的,因为它们并不真正使用“普通”CLR代码中的指针。 However, when you do require pointers, then you need to fix it in memory if you want to work with them. 但是,当你需要指针时,如果你想使用它们,你需要在内存中修复它。

The fixed statement will "pin" the variable in memory so that the garbage collector doesn't move it around when collecting. fixed语句将“固定”内存中的变量,以便垃圾收集器在收集时不会移动它。 If it did move the variable, the pointer would become useless and when you used it you'd be trying to access or modify something that you didn't intend to. 如果它确实移动了变量,指针将变得无用,当你使用它时,你将尝试访问或修改你不想要的东西。

你需要在指针算术的任何地方使用它,以防止垃圾收集器在你身上移动它。

Because you are running in unsafe mode (pointer), the fixed instruction allocate a specific memory space to that variable. 因为您在不安全模式(指针)中运行,所以固定指令会为该变量分配特定的内存空间。 If you didn't put the fixed instruction, the garbage collector could move in memory the variable anywhere, when he want. 如果你没有放入固定的指令,垃圾收集器可以随时随地在内存中移动变量。

Hope this help. 希望这有帮助。

MSDN has a very similar example. MSDN有一个非常相似的例子。 The fixed statement basically blocks garbage collection. fixed语句基本上阻止了垃圾收集。 In .Net if you use a pointer to a memory location the runtime can reallocate the object to a "better" location at any time. 在.Net中,如果使用指向内存位置的指针,运行时可以随时将对象重新分配到“更好”的位置。 SO if you want to access memory directly you need to fix it in place. 因此,如果您想直接访问内存,则需要将其修复到位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM