码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-10-09 14:05:43      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   sp   div   

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语句

标签:style   blog   http   color   io   os   ar   sp   div   

原文地址:http://www.cnblogs.com/Ares945/p/fixed.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!