C#:使用ref,out關鍵詞定義傳回值函數

來源:互聯網
上載者:User
代碼

static int xValue(ref int num, ref int num2)
        {
            num = 2 * num;
            num2 = 2 * num2;
            return num;
        }
        static void Main(string[] args)
        {
            int num = 5;
            int num2 = 10;
            Console.WriteLine(xValue(ref num, ref num2));
            Console.WriteLine(num + ":" + num2);
            //這時的num=10, num2=20;輸出結果:10:20;加上ref後會影響到函數外面的變數
        }

兩個注意點:
1:定義函數時.指定參數的資料類型與函數體外面定義的變數類型一致,static int xValue(ref int num, ref int num2)
2:使用此函數時為每個參數加上ref.如果不加的話則不會影響函數外面變數的值

代碼

static int MaxValueL(int[] numArry, out int maxIndex, out int maxIndex2)
        {
            int MaxValue = numArry[0];
            maxIndex = 0;
            maxIndex2 = 100;
            for (int i = 1; i < numArry.Length; i++)
            {
                if (MaxValue < numArry[i])
                {
                    MaxValue = numArry[i];
                    maxIndex = i;
                }
            }
            return MaxValue;
        }
        static void Main(string[] args)
        {
            int maxIndex;
            int maxIndex2;
            int[] numArr = { 14, 3, 34, 11, 99, 33 };
            Console.WriteLine(MaxValueL(numArr, out maxIndex, out maxIndex2));
            //返回函數體內的變數MaxValue
            Console.WriteLine(maxIndex + 1);
            //返回函數體內的變數maxIndex
            Console.WriteLine(maxIndex2);
            //返回函數體內的變數maxIndex2
            Console.ReadKey();
        }

 

兩個注意點:
1:定義函數時.指定輸出參數的資料類型與函數體外面定義的變數類型一致,out int maxIndex, out int maxIndex2
2:使用此函數時為想要輸出參數加上 out .
這裡的輸出是指把函數體內的變數輸出到函數體外應用.這也關聯到了變數的範圍問題.

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.