日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

C#语法之fixed 语句

發(fā)布時間:2025/3/20 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C#语法之fixed 语句 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

fixed 語句禁止垃圾回收器重定位可移動的變量。fixed 語句只能出現(xiàn)在不安全的上下文中。Fixed 還可用于創(chuàng)建固定大小的緩沖區(qū)。

fixed 語句設(shè)置指向托管變量的指針并在 statement 執(zhí)行期間“釘住”該變量。如果沒有 fixed 語句,則指向可移動托管變量的指針的作用很小,因?yàn)槔厥湛赡懿豢深A(yù)知地重定位變量。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; }

可以用數(shù)組或字符串的地址初始化指針:

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. } }

執(zhí)行完語句中的代碼后,任何固定變量都被解除固定并受垃圾回收的制約。因此,不要指向 fixed 語句之外的那些變量。

無法修改在 fixed 語句中初始化的指針。

在不安全模式中,可以在堆棧上分配內(nèi)存。堆棧不受垃圾回收的制約,因此不需要被鎖定。

// 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); } }

結(jié)果為:

25 6

轉(zhuǎn)載于:https://www.cnblogs.com/superfang/archive/2008/07/03/1235094.html

總結(jié)

以上是生活随笔為你收集整理的C#语法之fixed 语句的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。