Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Учебник_ПОА.doc
Скачиваний:
93
Добавлен:
13.02.2015
Размер:
2.65 Mб
Скачать

Компиляция кода

Скопируйте код и вставьте его в метод Main консольного приложения.

Надежное программирование

Элементы массива автоматически инициализируются значениями по умолчанию, если массив не был инициализирован во время объявления. Если массив объявлен как поле типа, то после создания типа массиву по умолчанию будет присвоено значение null.

How to: Pass Object Arrays to Methods

This example shows how an array of objects is passed to the DisplayMyCollection method, which uses the params keyword to accept any number of arguments.

Example

class MyBoxingClass

{

public static void DisplayMyCollection(params object[] anArray)

{

foreach (object obj in anArray)

{

System.Console.Write(obj + "\t");

}

// Suspend the screen.

System.Console.ReadLine();

}

static void Main()

{

DisplayMyCollection(101, "Visual C# Basics", 2002);

}

}

Compiling the Code

You can compile the example directly using the command line, or paste it into a console application.

Передача массивов объектов в метод

В следующем примере показана передача массива объектов в метод DisplayMyCollection, использующий ключевое слово params для принятия любого числа аргументов.

Пример

class MyBoxingClass

{

public static void DisplayMyCollection(params object[] anArray)

{

foreach (object obj in anArray)

{

System.Console.Write(obj + "\t");

}

// Suspend the screen.

System.Console.ReadLine();

}

static void Main()

{

DisplayMyCollection(101, "Visual C# Basics", 2002);

}

}

Компиляция кода

Пример можно скомпилировать непосредственно в командной строке либо вставить в консольное приложение.

Collections

An array is just one of many options for storing sets of data by using C#. The option that you select depends on several factors, such as how you intend to manipulate or access the items. For example, a list is generally faster than an array if you must insert items at the beginning or in the middle of the collection. Other types of collection classes include map, tree, and stack; each one has its own advantages. For more information, see System.Collections, and System.Collections.Generic.

The following example shows how to use the List<(Of <<T>)>> class. Notice that unlike the Array class, items can be inserted into the middle of the list. This example restricts the items in the list so that they must be strings.

public class TestCollections

{

public static void TestList()

{

System.Collections.Generic.List<string> sandwich = new System.Collections.Generic.List<string>();

sandwich.Add("bacon");

sandwich.Add("tomato");

sandwich.Insert(1, "lettuce");

foreach (string ingredient in sandwich)

{

System.Console.WriteLine(ingredient);

}

}

}