C# 中的 ref 和 out 的意義和使用方法

        向方法傳遞一個實參時,對應的形參會用實參的一個副本來初始化,不管形參是值類型(例如 int),可空類型(int?),還是引用類型,這一點都是成立的。也就是隨便在方法內部進行什麼修改,都不會影響實參的值。例如,對於引用類型,方法的改變,只是會改變引用的數據,但實參本身並沒有變化,它仍然引用同一個對象。

        代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ref_out
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 8;
            Console.WriteLine(i);
            DoIncrease(i);
            Console.WriteLine(i);
        }

        static void DoIncrease(int a)
        {
            a++;
        }
    }
}
        運行結果如下:



        若使用 ref 關鍵字,向形參應用的任何操作都同樣應用於實參,因爲形參和實參引用的是同一個對象。PS:實參和形參都必須附加 ref 關鍵字做爲前綴。

        代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ref_out
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 8;
            Console.WriteLine(i);   // 8
            DoIncrease(ref i);      // 實參前也必須加 ref
            Console.WriteLine(i);   // 9 // ref 關鍵字使對形參的動作也應用於實參
        }

        static void DoIncrease(ref int a)   // 形參前必須加 ref
        {
            a++;
        }
    }
}
        運行結果如下:

        ref 實參使用前也必須初始化,否則不能通過編譯。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ref_out
{
    class Program
    {
        static void Main(string[] args)
        {
            int i;          // ref 實參沒有初始化,所以程序不能通過編譯
            Console.WriteLine(i);
            DoIncrease(ref i);
            Console.WriteLine(i);
        }

        static void DoIncrease(ref int a)
        {
            a++;
        }
    }
}

        有時我們希望由方法本身來初始化參數,這時可以使用 out 參數。

        代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ref_out
{
    class Program
    {
        static void Main(string[] args)
        {
            int i;    // 沒有初始化
            //Console.WriteLine(i); // 此處 i 未初始化,編譯錯誤
            DoIncrease(out i);  // 用方法來給實參賦初值
            Console.WriteLine(i);
        }

        static void DoIncrease(out int a)
        {
            a = 8;  // 在方法中進行初始化
            a++;    // a = 9
        }
    }
}
        運行結果如下:


發佈了51 篇原創文章 · 獲贊 17 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章