Книга: C# 2008 Programmer

Parameter Arrays

Parameter Arrays

In C#, you can pass variable numbers of parameters into a function/method using a feature known as parameter arrays. Consider the following statements:

string firstName = "Wei-Meng";
string lastName = "Lee";
Console.WriteLine("Hello, {0}", firstName);
Console.WriteLine("Hello, {0} {1}", firstName, lastName);

Observe that the last two statements contain different numbers of parameters. In fact, the WriteLine() method is overloaded, and one of the overloaded methods has a parameter of type params (see Figure 13-3). The params keyword lets you specify a method parameter that takes an argument where the number of arguments is variable.


Figure 13-3

A result of declaring the parameter type to be of params is that callers to the method do not need to explicitly create an array to pass into the method. Instead, they can simply pass in a variable number of parameters.

To use the params type in your own function, you define a parameter with the params keyword:

private void PrintMessage(string prefix, params string[] msg) {
}

To extract the parameter array passed in by the caller, treat the params parameter like a normal array, like this:

private void PrintMessage(string prefix, params string[] msg) {
 foreach (string s in msg)
  Console.WriteLine("{0}>{1}", prefix, s);
}

When calling the PrintMessage() function, you can pass in a variable number of parameters:

PrintMessage("C# Part 1", "Arrays", "Index", "Collections");
PrintMessage("C# Part 2", "Objects", "Classes");

These statements generate the following output:

C# Part 1>Arrays
C# Part 1>Index
C# Part 1>Collections
C# Part 2>Objects
C# Part 2>Classes

A params parameter must always be the last parameter defined in a method declaration.

Оглавление книги


Генерация: 0.861. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз