Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Создание класса Writer

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

using System;

using System.IO;

public class MyWriter

{

private Stream s;

public MyWriter(Stream stream)

{

s = stream;

}

public void WriteDouble(double myData)

{

byte[] b = BitConverter.GetBytes(myData);

// GetBytes is a binary representation of a double data type.

s.Write(b, 0, b.Length);

}

public void Close()

{

s.Close();

}

}

В этом примере создается класс с конструктором, аргументом которого является поток. Поэтому есть возможность в дальнейшем обращаться к любым необходимым методам Write. Необходимо преобразовать данные, предназначенные для записи, в массив byte[]. После получения массива byte[] метод Write записывает его в поток s.

Collections and Data Structures

Closely related data can be handled more efficiently when grouped together into a collection. Instead of writing separate code to handle each individual object, you can use the same code to process all the elements of a collection.

To manage a collection, use the Array class and the System.Collections classes to add, remove, and modify either individual elements of the collection or a range of elements. An entire collection can even be copied to another collection.

Some Collections classes have sorting capabilities, and most are indexed. Memory management is handled automatically, and the capacity of a collection is expanded as required. Synchronization provides thread safety when accessing members of the collection. Some Collections classes can generate wrappers that make the collection read-only or fixed-size. Any Collections class can generate its own enumerator that makes it easy to iterate through the elements.

In the .NET Framework version 2.0, generic collection classes provide new functionality and make it easy to create strongly typed collections. See the System.Collections.Generic and System.Collections.ObjectModel namespaces.

The LINQ to Objects feature allows you to use LINQ queries to access in-memory objects as long as the object type implements IEnumerable or IEnumerable<(Of <(T>)>). LINQ queries provide a common pattern for accessing data; are typically more concise and readable than standard foreach loops; and provide filtering, ordering and grouping capabilities. LINQ queries can also improve performance.

Коллекции и структуры данных

Связанные данные могут обрабатываться более эффективно, если они объединены в коллекцию. Вместо того чтобы писать код для обработки каждого отдельного объекта, можно использовать один и тот же код для обработки всех элементов коллекции.

Для управления коллекцией используйте класс Array и классы из пространства имен System.Collections для добавления, удаления и изменения либо отдельных элементов коллекции, либо диапазона элементов. Коллекцию можно скопировать целиком в другую коллекцию.

Некоторые классы коллекций предоставляют возможность сортировки, и большинство из них индексированы. Управление памятью осуществляется автоматически, а вместимость коллекции увеличивается по мере необходимости. Синхронизация обеспечивает потокобезопасность при доступе к членам коллекции. Некоторые классы коллекций могут создавать оболочки, поодерживающие фиксированный размер коллекции или ограничение доступа к членам коллекции только чтением. Любой класс коллекций может создать свой собственный нумератор, облегчающий выполнение итерации элементов.

В .NET Framework, версия 2.0 классы универсальных коллекций предоставляют новые функциональные возможности и облегчают создание строго типизированных коллекций. Обратитесь к описанию пространств имен System.Collections.Generic и System.Collections.ObjectModel.

Функция LINQ to Objects позволяет использовать LINQ запросы для доступа к объектам в памяти, если объект типа реализовывает IEnumerable или IEnumerable<(Of <(T>)>). LINQ запросы предоставляют общий шаблон для доступа к данным, являются более четкими и удобочитаемыми, чем стандартные циклы foreach, а также предоставляют возможности фильтрации, сортировки и группировки. LINQ запросы также могут повысить производительность.

Defining Collections

A collection is a set of similarly typed objects that are grouped together.

Objects of any type can be grouped into a single collection of the type Object to take advantage of constructs that are inherent in the language. For example, the C# foreach statement (for each in Visual Basic) expects all objects in the collection to be of a single type.

However, in a collection of type Object, additional processing is done on the elements individually, such as boxing and unboxing or conversions, which affect the performance of the collection. Boxing and unboxing typically occur if storing or retrieving a value type in a collection of type Object.

Generic collections, such as List<(Of <(T>)>), and strongly typed nongeneric collections, such as StringCollection, avoid these performance hits if the type of the element is the type that the collection is intended for (for example, storing or retrieving strings from a StringCollection). In addition, strongly typed collections automatically perform type validation of each element added to the collection.

All collections that directly or indirectly implement the ICollection interface or the ICollection<(Of <(T>)>) generic interface share several features in addition to methods that add, remove, or search elements:

  • An enumerator.

An enumerator is an object that iterates through its associated collection. It can be thought of as a movable pointer to any element in the collection. An enumerator can be associated with only one collection, but a collection can have multiple enumerators. The C# foreach statement (for each in Visual Basic) uses the enumerator and hides the complexity of manipulating the enumerator.

  • Synchronization members.

Synchronization provides thread safety when accessing elements of the collection. The collections are not thread safe by default. Only a few classes in the System.Collections namespaces provide a Synchronize method that creates a thread-safe wrapper over the collection. However, all classes in all System.Collections namespaces provide a SyncRoot property that can be used by derived classes to create their own thread-safe wrapper. An IsSynchronized property is also provided to determine whether the collection is thread safe. Synchronization is not available in the ICollection<(Of <(T>)>) generic interface.

  • The CopyTo method.

All collections can be copied to an array using the CopyTo method; however, the order of the elements in the new array is based on the sequence in which the enumerator returns them. The resulting array is always one-dimensional with a lower bound of zero.

Note that the ICollection<(Of <(T>)>) generic interface has additional members, which the nongeneric interface does not include.