C#语法之fixed 语句
生活随笔
收集整理的這篇文章主要介紹了
C#语法之fixed 语句
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
fixed 語句禁止垃圾回收器重定位可移動的變量。fixed 語句只能出現在不安全的上下文中。Fixed 還可用于創建固定大小的緩沖區。
fixed 語句設置指向托管變量的指針并在 statement 執行期間“釘住”該變量。如果沒有 fixed 語句,則指向可移動托管變量的指針的作用很小,因為垃圾回收可能不可預知地重定位變量。C# 編譯器只允許在 fixed 語句中分配指向托管變量的指針。
// assume class Point { public int x, y; } // pt is a managed variable, subject to garbage collection. Point pt = new Point(); // Using fixed allows the address of pt members to be // taken, and "pins" pt so it isn't relocated. fixed ( int* p = &pt.x ) { *p = 1; }可以用數組或字符串的地址初始化指針:
fixed (int* p = arr) ... // equivalent to p = &arr[0] har* p = str) ... // equivalent to p = &str[0]只要指針的類型相同,就可以初始化多個指針:
fixed (byte* ps = srcarray, pd = dstarray) {...}要初始化不同類型的指針,只需嵌套 fixed 語句:
fixed (int* p1 = &p.x) { d (double* p2 = &array[5]) { // Do something with p1 and p2. } }執行完語句中的代碼后,任何固定變量都被解除固定并受垃圾回收的制約。因此,不要指向 fixed 語句之外的那些變量。
無法修改在 fixed 語句中初始化的指針。
在不安全模式中,可以在堆棧上分配內存。堆棧不受垃圾回收的制約,因此不需要被鎖定。
// statements_fixed.cs // compile with: /unsafe using System; ? class Point { public int x, y; } ? class FixedTest { // Unsafe method: takes a pointer to an int. unsafe static void SquarePtrParam (int* p) { *p *= *p; } ? unsafe static void Main() { Point pt = new Point(); pt.x = 5; pt.y = 6; // Pin pt in place: fixed (int* p = &pt.x) { SquarePtrParam (p); } // pt now unpinned Console.WriteLine ("{0} {1}", pt.x, pt.y); } }結果為:
25 6轉載于:https://www.cnblogs.com/superfang/archive/2008/07/03/1235094.html
總結
以上是生活随笔為你收集整理的C#语法之fixed 语句的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转]基于Prototype,利用Can
- 下一篇: 查看网关物理地址命令