共用方式為


fixed 陳述式 (C# 參考)

fixed 陳述式可讓記憶體回收行程避免重新配置可移動的變數。 fixed 陳述式只允許在 unsafe 內容中。 Fixed 也可用來建立固定大小緩衝區

fixed 陳述式會設定一個指標至 Managed 變數,並在陳述式執行期間將此變數固定住。 如果沒有 fixed,Managed 變數的指標也許沒有多大用處,因為記憶體回收可能會在非預期下重新配置變數。 C# 編譯器只能讓您將指標指派到 fixed 陳述式中的 Managed 變數。

unsafe static void TestMethod()
{

    // Assume that the following class exists.
    //class Point 
    //{ 
    //    public int x;
    //    public int y; 
    //}

    // Variable 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 that it is not relocated.

    fixed (int* p = &pt.x)
    {
        *p = 1;
    }        

}

您可以使用陣列、字串、固定大小的緩衝區或變數的位址初始化指標。 下列範例說明變數位址、陣列和字串的用法。 如需關於固定大小緩衝區的詳細資訊,請參閱固定大小緩衝區 (C# 程式設計手冊).

static unsafe void Test2()
{
    Point point = new Point();
    double[] arr = { 0, 1.5, 2.3, 3.4, 4.0, 5.9 };
    string str = "Hello World";

    // The following two assignments are equivalent. Each assigns the address
    // of the first element in array arr to pointer p.

    // You can initialize a pointer by using an array.
    fixed (double* p = arr) { /*...*/ }

    // You can initialize a pointer by using the address of a variable. 
    fixed (double* p = &arr[0]) { /*...*/ }

    // The following assignment initializes p by using a string.
    fixed (char* p = str) { /*...*/ }

    // The following assignment is not valid, because str[0] is a char, 
    // which is a value, not a variable.
    //fixed (char* p = &str[0]) { /*...*/ } 


    // You can initialize a pointer by using the address of a variable, such
    // as point.x or arr[5].
    fixed (int* p1 = &point.x)
    {
        fixed (double* p2 = &arr[5])
        {
            // Do something with p1 and p2.
        }
    }
}

只要都有相同的型別,您就可以初始化多個指標。

fixed (byte* ps = srcarray, pd = dstarray) {...}

若要初始化不同型別的指標,只需將 fixed 陳述式巢狀化,如下列範例所示。

fixed (int* p1 = &point.x)
{
    fixed (double* p2 = &arr[5])
    {
        // Do something with p1 and p2.
    }
}

執行陳述式中的程式碼後,任何已固定的變數將取消固定並且交付記憶體回收。 因此請不要指向 fixed 陳述式之外的變數。

注意事項注意事項

不能修改在 fixed 陳述式中初始化的指標。

在不安全模式,您可以配置在堆疊上的記憶體;那裡並不需要交付給記憶體回收,因此不需要固定。 如需詳細資訊,請參閱 stackalloc

範例

    class Point
    { 
        public int x, y; 
    }

    class FixedTest2 
    {
        // 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);
        }
    }
    /*
    Output:
    25 6
     */

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格。語言規格是 C# 語法和用法的限定來源。

請參閱

參考

C# 關鍵字

unsafe (C# 參考)

固定大小緩衝區 (C# 程式設計手冊)

概念

C# 程式設計手冊

其他資源

C# 參考