C#方法中三個重要的參數:out、ref、params

來源:互聯網
上載者:User

標籤:

備忘:適用於初學者,自學於傳智播客。

1.out參數。

  概念:如果在一個方法中,返回多個相同類型值的時候,可以考慮返回一數組。但是返回多個不同類型值的時候,返回數組顯然不能解決問題,這時就引入out參數。out參數側重於在一個方法中可以返回多個不同類型的值。

  代碼舉例:

使用者登陸:   

    main:Test(numbers, out max1, out min1, out sum1, out avg1, out b, out s, out d); 

    方法:public static void Test(int[] nums, out int max, out int min, out int sum, out int avg, out bool b, out string s, out double d)
       {...}

2.ref參數。

  概念:能夠將一個變數帶入一個方法中進行改變,改變完成後再將改變後的值帶出方法,ref參數要求在方法外必須為其賦值,而方法內可以不賦值。

  代碼舉例:

    main:Test(ref n1, ref  n2); 

    方法:public static void Test(ref int n1, ref  int n2)
       {...}

3.params可變參數。

  概念:將實參列表中跟可變參數數群組類型一致的元素都當做數組的元素去處理。params可變參數必須是形參列表中的最後一個元素。

  代碼舉例:

    main:Test("張三",158412,100,100,100);

    方法:public static void Test(string name, int id, params int[] score)
       {...}

C#方法中三個重要的參數:out、ref、params

聯繫我們

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