為了將方法聲明為可以接受可變數(shù)量參數(shù)的方法,,我們可以使用params關(guān)鍵字來(lái)聲明數(shù)組,要求: (1)在方法聲明中的 params 關(guān)鍵字之后不允許任何其他參數(shù),,并且在方法聲明中只允許一個(gè) params 關(guān)鍵字,。 (2)該參數(shù)必須標(biāo)識(shí)一個(gè)一維數(shù)組,,但類(lèi)型不限,對(duì)該參數(shù)傳遞null或者0個(gè)數(shù)目的數(shù)組的引用都是合法的 01 — 實(shí)例1 using System;
namespace ConsoleApp4 { class Program { static void Main(string[] args) { ShowTime(new string[]{ "1","2","3","4","5","6","7","8","9"}); Console.ReadKey(); } private static void ShowTime(params string[] strs) { foreach (var str in strs) { Console.WriteLine(str.ToString()); } } } }
運(yùn)行結(jié)果: 02 — 實(shí)例2 using System;
namespace ConsoleApp4 { class Program { static void Main(string[] args) { //ShowTime(new string[]{ "1","2","3","4","5","6","7","8","9"}); ShowTypes(new object(), new Random(), new string[] { }, 123,'a'); Console.ReadKey(); } private static void ShowTime(params string[] strs) { foreach (var str in strs) { Console.WriteLine(str.ToString()); } } public static void ShowTypes(params object[] objects) { foreach (var item in objects) { Console.WriteLine(item.GetType()); } } } }
運(yùn)行結(jié)果: 注意:對(duì)于可接受可變數(shù)量參數(shù)的方法的調(diào)用會(huì)對(duì)性能造成一定的損失,因?yàn)閿?shù)組是在堆上分配的,,數(shù)組的元素還得初始化,,數(shù)組的內(nèi)存還得被垃圾回收器回收 |
|
來(lái)自: ontheroad96j47 > 《待分類(lèi)》