方法參數修飾符ref和out的區別

來源:互聯網
上載者:User
out和ref

1)out和ref傳變數的地址(引用地址),形參改變,實參也改變。因為他們都是引用一個地址的;
2)帶ref和out修飾的參數只能傳遞變數不能傳遞常量.
3)out和ref的區別
  out修飾的參數必須在方法內修改,而ref可以修改也可以不修改;
  out在傳入參數的時候,參數是局部變數的話,可以不用賦值,因為out一定會對其進行賦值;
  而ref修飾的參數,在實參必須有初始值才能調用。因為ref修飾的不一定會給它賦值。

上代碼:

 class Program    {        static void Main(string[] args)        {            int[] zs = { 3, 13, 6, 45, 6, 7, 99, 179 };            //區別,使用ref修飾的參數,再使用前必須賦初始值;            int min=0, max;            //調用方法的時候也要加ref和max            GetMinAndMax(zs,ref min,out max);            Console.WriteLine("這個數組中最大的值是{0},最小的值是{1}",max,min);            Console.ReadKey();        }               #region out參數求數組中最大值和最小值        static void GetMinAndMax(int[] nums, ref int min, out int max)        {            //傳入數組為空白,則返回0            if (nums == null)            {                min = 0;                max = 0;                return;            }            //冒泡排序:面試用,             //實際開發:Array.Sort(nums);            for (int i = 0; i < nums.Length - 1; i++)            {                for (int j = 0; j < nums.Length - 1 - i; j++)                {                    if (nums[j] > nums[j + 1])                    {                        int temp = nums[j];                        nums[j] = nums[j + 1];                        nums[j + 1] = temp;                    }                }            }            //找出兩個數            min = nums[0];            max = nums[nums.Length - 1];        }        #endregion    }



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.