C# 的 params

params 是类似于以前 C 中的 ... ,指的是不确定数量的参数。

params 可以用于函数或方法的 最后一个参数,代表后面是一串数量不定的参数。

params 等同于 new object[],但用了 params时,就不用那么麻烦写 new object[] {}了。

如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace testParams
 7 {
 8     class Program
 9     {
10         void testParams(params object[] args)
11         {
12             foreach (string s in args)
13             {
14                 Console.WriteLine("{0} is {1}", Array.IndexOf(args, s), s);
15             }
16         }
17 
18         void test2()
19         {
20             testParams(new object[] { "hahah are you ok?", "hahah this is me", "hahah pencilstart", "hahah a superme." });
21         }
22 
23         void test1()
24         {
25             testParams("are you ok?", "this is me", "pencilstart", "a superme.");
26         }
27 
28         static void Main(string[] args)
29         {
30             Program p = new Program();
31 
32             p.test1();
33 
34             Console.WriteLine("----");
35 
36             p.test2();
37         }
38     }
39 
40 
41 }
42 
43 // 以下是运行结果======================
44 
45 //0 is are you ok?
46 //1 is this is me
47 //2 is pencilstart
48 //3 is a superme.
49 //----
50 //0 is hahah are you ok?
51 //1 is hahah this is me
52 //2 is hahah pencilstart
53 //3 is hahah a superme.
54 //请按任意键继续. . .

 

posted @ 2020-11-28 16:13  PencilStart  阅读(1579)  评论(0编辑  收藏  举报