C#需知--長度可變參數--Params

來源:互聯網
上載者:User

標籤:style   blog   http   ar   color   使用   sp   for   on   

Params用於參數的數量可變的情況下,即參數的個數是未知數。

使用Params需要知道以下幾點:

1、如果函數傳遞的參數含有多個,使用Params標記的參數數組需要放在最後

圖上顯示的很明確,不需要多解釋,只能使用A的那種排序方式

2、Params修飾的一定要是數組,而且必須是一維數組

3、Params不能和ref、out組合使用

具體參見Hunts.C前輩的文章http://www.cnblogs.com/hunts/archive/2007/01/13/619620.html

4、與Params修飾的參數數組對應的實參可以是同一類型的數組名(注意:只能是一個數組名,多個數組名是不可以的),也可以是任意多個與該數組的元素屬於同一類型的變數

示範代碼

class Program    {        static void Main(string[] args)        {            //展示參數是可變的            int i = Sum(1, 13, 23, 34);            Console.WriteLine(i);            int j = Sum(1, 1, 3, 2, 4, 4, 44, 555, 6);            Console.WriteLine(j);            //實參可以是數組名            int[] ArrayI = new int[5] { 1, 2, 3, 4, 5 };            int ArraySum = Sum(ArrayI);            Console.WriteLine(ArraySum);            Console.Read();        }        static int Sum(params int[] s)        {            int sum = 0;            foreach(int i in s)            {                                sum += i;            }            return sum;        }    }

 

C#需知--長度可變參數--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.