在C#中的固定语句 [英] Fixed Statement in C#

查看:163
本文介绍了在C#中的固定语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们也有类似的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.

这篇关于在C#中的固定语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆