C # basic keywords-fixed statements

Source: Internet
Author: User

1、该语句用于“固定”可移动变量,从而使该变量的地址在语句的持续时间内保持不变。只有执行完fixed块后,指针所指向的对象才可以移动。

 1 unsafe static void TestMethod() 2 { 3  4     // Assume that the following class exists. 5     //class Point  6     //{  7     //    public int x; 8     //    public int y;  9     //}10 11     // Variable pt is a managed variable, subject to garbage collection.12     Point pt = new Point();13 14     // Using fixed allows the address of pt members to be taken,15     // and "pins" pt so that it is not relocated.16 17     fixed (int* p = &pt.x)18     {19         *p = 1;20     }        21 22 }

 

由 fixed 语句声明的局部变量被视为只读。 如果嵌入语句试图修改此局部变量(通过赋值或 ++ 和 -- 运算符)或者将它作为 ref 或 out 参数传递,则将出现编译时错误。

固定对象可能导致堆中产生存储碎片(因为它们无法移动),出于该原因,只有在绝对必要时才应当固定对象,而且固定对象的时间越短越好。

2、固定大小的缓冲区

http://msdn.microsoft.com/zh-cn/library/zycewsya.aspx

C#基础关键字篇-fixed语句

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.