params (C# 參考)
使用 params
關鍵字,您可以指定方法參數,其採用可變數目的引數。 參數類型必須是單一維度陣列。
在方法宣告中,params
關鍵字後面不允許任何其他參數,而且方法宣告中只允許一個 params
關鍵字。
如果參數的 params
宣告類型不是單維陣列,則會發生編譯器錯誤 CS0225 。
當您使用 params
參數呼叫方法時,可以傳入:
- 陣列專案型別的引數逗號分隔清單。
- 指定型別的引數陣列。
- 無引數。 如果不傳送任何引數,
params
清單的長度為零。
範例
下例示範將引數傳送至 params
參數的各種方式。
public class MyClass
{
public static void UseParams(params int[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
public static void UseParams2(params object[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
static void Main()
{
// You can send a comma-separated list of arguments of the
// specified type.
UseParams(1, 2, 3, 4);
UseParams2(1, 'a', "test");
// A params parameter accepts zero or more arguments.
// The following calling statement displays only a blank line.
UseParams2();
// An array argument can be passed, as long as the array
// type matches the parameter type of the method being called.
int[] myIntArray = { 5, 6, 7, 8, 9 };
UseParams(myIntArray);
object[] myObjArray = { 2, 'b', "test", "again" };
UseParams2(myObjArray);
// The following call causes a compiler error because the object
// array cannot be converted into an integer array.
//UseParams(myObjArray);
// The following call does not cause an error, but the entire
// integer array becomes the first element of the params array.
UseParams2(myIntArray);
}
}
/*
Output:
1 2 3 4
1 a test
5 6 7 8 9
2 b test again
System.Int32[]
*/
C# 語言規格
如需詳細資訊,請參閱 C# 語言規格。 語言規格是 C# 語法及用法的限定來源。