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.
To copy from one array to another, use the Copy()
method from the Array
abstract base class:
int[] num = new int[5] { 1, 2, 3, 4, 5 };
int[] num1 = new int[5];
num.CopyTo(num1, 0);
These statements copy all the elements from the num
array into the num1
array. The second parameter in the CopyTo()
method specifies the index in the array at which the copying begins.
The System.Collections
namespace contains several interfaces that define basic collection functionalities:
The interfaces described in the following list are the generic versions of the respective interfaces. Beginning with C# 2.0, you should always try to use the generic versions of the interfaces for type safety. Chapter 9 discusses the use of generics in the C# language.
Interface |
Description |
IEnumerable and IEnumerator |
Enable you to loop through the elements in a collection. |
ICollection |
Contains items in a collection and provides the functionality to copy elements to an array. Inherits from IEnumerable . |
IComparer and IComparable |
Enable you to compare objects in a collection. |
IList |
Inherits from ICollection and provides functionality to allow members to be accessed by index. |
IDictionary |
Similar to IList , but members are accessed by key value rather than index. |
The ICollection
interface is the base interface for classes in the System.Collections
namespace.
Dynamic Arrays Using the ArrayList Class
Arrays in C# have a fixed size once they are initialized. For example, the following defines a fixed- size array of five integer elements:
int[] num = new int[5];
If you need to dynamically increase the size of an array during runtime, use the ArrayList
class instead. You use it like an array, but its size can be increased dynamically as required.
The ArrayList
class is located within the System.Collections
namespace, so you need to import that System.Collections
namespace before you use it. The ArrayList
class implements the IList
interface.
To use the ArrayList
class, you first create an instance of it:
ArrayList arrayList = new ArrayList();
Use the Add()
method to add elements to an ArrayList
object:
arrayList.Add("Hello");
arrayList.Add(25);
arrayList.Add(new Point(3,4));
arrayList.Add(3.14F);
Notice that you can add elements of different types to an ArrayList
object.
To access an element contained within an ArrayList
object, specify the element's index like this:
Console.WriteLine(arrayList[0]); //---Hello---
Console.WriteLine(arrayList[1]); //---25---
Console.WriteLine(arrayList[2]); //---{X=3,Y=4}
Console.WriteLine(arrayList[3]); //---3.14---
The ArrayList
object can contain elements of different types, so when retrieving items from an ArrayList
object make sure that the elements are assigned to variables of the correct type. Elements retrieved from an ArrayList
object belong to Object
type.
You can insert elements to an ArrayList
object using the Insert()
method:
arrayList.Insert(1, " World!");
After the insertion, the ArrayList
object now has five elements:
Console.WriteLine(arrayList[0]); //---Hello---
Console.WriteLine(arrayList[1]); //---World!---
Console.WriteLine(arrayList[2]); //---25---
Console.WriteLine(arrayList[3]); //---{X=3,Y=4}---
Console.WriteLine(arrayList[4]); //---3.14---
To remove elements from an ArrayList
object, use the Remove()
or RemoveAt()
methods:
arrayList.Remove("Hello");
arrayList.Remove("Hi"); //---cannot find item---
arrayList.Remove(new Point(3, 4));
arrayList.RemoveAt(1);
After these statements run, the ArrayList
object has only two elements:
Console.WriteLine(arrayList[0]); //---World!---
Console.WriteLine(arrayList[1]); //---3.14---
If you try to remove an element that is nonexistent, no exception is raised (which is not very useful). It would be good to use the Contains()
method to check whether the element exists before attempting to remove it:
if (arrayList.Contains("Hi")) arrayList.Remove("Hi");
else Console.WriteLine("Element not found.");
You can also assign the elements in an ArrayList
object to an array using the ToArray()
method:
object[] objArray;
objArray = arrayList.ToArray();
foreach (object o in objArray)
Console.WriteLine(o.ToString());
Because the elements in the ArrayList
can be of different types you must be careful handling them or you run the risk of runtime exceptions. To work with data of the same type, it is more efficient to use the generic equivalent of the ArrayList
class — the List
class, which is type safe. To use the List
class, you simply instantiate it with the type you want to use and then use the different methods available just like in the ArrayList
class:
Читать дальше