在C#中的固定语句

人气:1,172 发布:2022-09-10 标签: memory-management .net c# garbage-collection unsafe

问题描述

我们也有类似的code到我们的项目之一以下。谁能解释(以简单的英语)为何固定语句需要在这里?

 类的TestClass
{
    INT iMyVariable;
    静态无效的主要()
    {
        TestClass的oTestClass =新的识别TestClass();
        不安全
        {
            固定(INT * P =安培; oTestClasst.iMyVariable)
            {
                * P = 9;
            }
        }
    }
}
 

解决方案

它修复了该指针在内存中。垃圾收集的语言可以自由地移动物体周围的记忆效率。这一切都是透明的,程序员,因为他们并不真正使用指针在正常CLR code。但是,当你需要指针,那么你需要的,如果你想与他们合作来解决它在内存中。

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. However, when you do require pointers, then you need to fix it in memory if you want to work with them.

122