在c#中ref 和 out關鍵字的聯繫和區別

聯繫

out:輸出參數;ref:引用參數;
兩者都是按地址傳遞的,使用後都將改變原來參數的數值,且使用方式幾乎相同,即在函數定義和函數調用中用作參數的修飾符,實際上,out的執行方式與引用參數幾乎完全一樣,因爲在函數執行完畢後,該參數的值將返回給函數調用中使用的變量。

區別

  • 把未賦值的變量用作ref參數是非法的,但可以把未賦值的變量用out參數。
  • 另外, 在參數中使用out參數時候,必須把它看成尚未賦值。如果想讓一個方法返回多個值可以用out參數來處理,即調用代碼可以把已經賦值的變量用作out參數,但存儲在該變量中的值會在函數執行時丟失。

ref實例

交換兩個數

namespace lesson1
{
    public class myClass
    {
        public void swap (ref int a, ref int b)
        {
            int temp = a;
            a = b;
            b = temp;
        }
    }


    class MainClass
    {
        public static void Main (string[] args)
        {

            myClass c = new myClass ();
            Console.WriteLine (c.sum (3, 5));
            int i = 5;
            int j = 12;
            c.swap (ref i, ref j);
            Console.WriteLine ("i= " + i + " j = " + j);
        }
    }
}

out實例

確定數組中第一個出現最大值的位置

namespace lesson1
{
    class MainClass
    {
        static int MaxValue (int[] intArray, out int maxIndex)
        {
            int maxVal = intArray [0];
            maxIndex = 0;
            for (int i = 1; i < intArray.Length; i++) {
                if (intArray [i] > maxVal) {
                    maxVal = intArray [i];
                    maxIndex = i;
                }
            }
            return maxVal;
        }

        public static void Main (string[] args)
        {
            int[] myArray = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 };
            int maxIndex;
            Console.WriteLine ("max is " + MaxValue (myArray, out maxIndex));
            int first = maxIndex + 1;
            Console.WriteLine ("第一個出現最大值的位置是" + first);

        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章