C#函數可變參數的使用

來源:互聯網
上載者:User

一般情況下,函數中參數是確定的。但是在某些情況下,函數的參數個數可以根據需要改變而改變,可變參數的函數使用方法是在參數前加params。

以下是我的一個demo:

查看代碼

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace demo
7 {
8 class Program
9 {
10 static void Vfunc(params string[] values)
11 {
12 foreach (string s in values)
13 {
14 Console.WriteLine(s);
15 }
16 }
17
18 static void Main(string[] args)
19 {
20 string[] names = {"zhm"};
21 string[] sexs = { "男", "女" };
22 Vfunc(names);
23 Vfunc(sexs);
24 Console.ReadKey();
25 }
26 }
27 }

//輸出zhm

         男

         女

當然,一個函數也可包含可變參數和不變參數,兩個可以同時使用

查看代碼

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace demo
7 {
8 class Program
9 {
10
11 static void SayHello(string name, params string[] nichens)
12 {
13 Console.WriteLine("我的名字{0}",name);
14 foreach(string nichen in nichens)
15 {
16 Console.WriteLine("我的暱稱{0}",nichen);
17 }
18 }
19 static void Main(string[] args)
20 {
21 string[] names = {"zhm","dd","yy","ii","UU" };
22 SayHello("zhm", names);
23
24 Console.ReadKey();
25 }
26 }
27 }

但是值得注意的是可變參數必須放在函數中參數位置的最後一個,上述函數如果寫成 static void SayHello(params string[] nichens,string name)

就會顯示錯誤:“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.