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

Выбор класса коллекции

Необходимо тщательно выбирать ваш класс System.Collections. Использование неправильного типа может привести к ограничению возможностей использования коллекции.

Необходимо ответить на следующие вопросы:

  • Нужен ли последовательный список, элемент которого обычно удаляется сразу после извлечения его значения?

    • Если да, то рассмотрите возможность использования класса Queue или универсального класса Queue<(Of <(T>)>), если требуется поведение по принципу "первым поступил — первым обслужен" (FIFO). Рассмотрите возможность использования класса Stack или универсального класса Stack<(Of <(T>)>), если требуется поведение по принципу "последним поступил — первым обслужен" (LIFO).

    • Если нет, то следует выбирать из остальных типов коллекций.

  • Нужен ли доступ к элементам в определенном или в произвольным порядке (FIFO, LIFO)?

    • Класс Queue и универсальный класс Queue<(Of <(T>)>) предоставляют доступ по принципу FIFO.

    • Класс Stack и универсальный класс Stack<(Of <(T>)>) предоставляют доступ по принципу LIFO.

    • Универсальный класс LinkedList<(Of <(T>)>) предоставляет последовательный доступ от начала к концу списка или наоборот.

    • Остальные коллекции предоставляют произвольный доступ.

  • Необходимо ли иметь доступ к каждому элементу по индексу?

    • Классы ArrayList и StringCollection, и универсальный класс List<(Of <(T>)>) предоставляют доступ к своим элементам по индексу с отсчетом от нуля.

    • Классы Hashtable, SortedList, ListDictionary и StringDictionary, а также универсальные классы Dictionary<(Of <(TKey, TValue>)>) и SortedDictionary<(Of <(TKey, TValue>)>) предоставляют доступ к своим элементам по ключу.

    • Классы NameObjectCollectionBase и NameValueCollection, а также универсальные классы KeyedCollection<(Of <(TKey, TItem>)>) и SortedList<(Of <(TKey, TValue>)>) предоставляют доступ к своим элементам по индексу с отсчетом от нуля или по ключу.

  • Will each element contain one value, a combination of one key and one value, or a combination of one key and multiple values?

    • One value: Use any of the collections based on the IList interface or the IList<(Of <(T>)>) generic interface.

    • One key and one value: Use any of the collections based on the IDictionary interface or the IDictionary<(Of <(TKey, TValue>)>) generic interface.

    • One value with embedded key: Use the KeyedCollection<(Of <(TKey, TItem>)>) generic class.

    • One key and multiple values: Use the NameValueCollection class.

  • Do you need to sort the elements differently from how they were entered?

    • The Hashtable class sorts its elements by their hash codes.

    • The SortedList class and the SortedDictionary<(Of <(TKey, TValue>)>) and SortedList<(Of <(TKey, TValue>)>) generic classes sort their elements by the key, based on implementations of the IComparer interface and the IComparer<(Of <(T>)>) generic interface.

    • ArrayList provides a Sort method that takes an IComparer implementation as a parameter. Its generic counterpart, the List<(Of <(T>)>) generic class, provides a Sort method that takes an implementation of the IComparer<(Of <(T>)>) generic interface as a parameter.

  • Do you need fast searches and retrieval of information?

    • ListDictionary is faster than Hashtable for small collections (10 items or fewer). The Dictionary<(Of <(TKey, TValue>)>) generic class provides faster lookup than the SortedDictionary<(Of <(TKey, TValue>)>) generic class.

  • Do you need collections that accept only strings?

    • StringCollection (based on IList) and StringDictionary (based on IDictionary) are in the System.Collections.Specialized namespace.

    • In addition, you can use any of the generic collection classes in the System.Collections.Generic namespace as strongly typed string collections by specifying the String class for their generic type arguments.

  • Будет ли каждый элемент содержать только одно значение, сочетание из одного ключа и одного значения или сочетание из одного ключа и нескольких значений?

    • Одно значение. Можно использовать любую из коллекций, основанных на интерфейсе IList или на универсальном интерфейсе IList<(Of <(T>)>).

    • Один ключ и одно значение. Можно использовать любую из коллекций, основанных на интерфейсе IDictionary или на универсальном интерфейсе IDictionary<(Of <(TKey, TValue>)>).

    • Одно значение с внедренным ключом. Можно использовать универсальный класс KeyedCollection<(Of <(TKey, TItem>)>).

    • Один ключ и несколько значений. Можно использовать класс NameValueCollection.

  • Нужна ли возможность отсортировать элементы в порядке, отличном от порядка их поступления?

    • Класс Hashtable сортирует свои элементы по их хэш-коду.

    • Класс SortedList и универсальные классы SortedDictionary<(Of <(TKey, TValue>)>) и SortedList<(Of <(TKey, TValue>)>) сортируют свои элементы по их ключам на основе реализации интерфейса IComparer и универсального интерфейса IComparer<(Of <(T>)>).

    • ArrayList предоставляет метод Sort, который принимает реализацию IComparer в качестве параметра. Его универсальный аналог — универсальный класс List<(Of <(T>)>) предоставляет метод Sort, который принимает реализацию универсального интерфейса IComparer<(Of <(T>)>) в качестве параметра.

  • Необходим ли быстрый поиск и извлечение данных?

    • ListDictionary быстрее, чем Hashtable для небольших коллекций (10 элементов или меньше). Универсальный класс Dictionary<(Of <(TKey, TValue>)>) предоставляет более быстрый просмотр, чем универсальный класс SortedDictionary<(Of <(TKey, TValue>)>).

  • Нужна ли коллекция только для хранения строк?

    • Классы StringCollection (основанный на IList) и StringDictionary (основанный на IDictionary) находятся в пространстве имен System.Collections.Specialized.

    • Кроме того, можно использовать любой из универсальных классов коллекций в пространстве имен System.Collections.Generic как строго типизированную строковую коллекцию, указав класс String в качестве аргумента универсального типа.

Introduction to Solutions, Projects, and Items

Visual Studio provides two containers to help you efficiently manage the items that are required by your development effort, such as references, data connections, folders, and files. These containers are called solutions and projects. Also, Visual Studio provides Solution Folders to organize related projects into groups and then perform actions on those groups of projects. Solution Explorer, an interface for viewing and managing these containers and their associated items, is part of the integrated development environment (IDE).

Containers: Solutions and Projects

Solutions and projects contain items that represent the references, data connections, folders, and files that you need to create your application. A solution can contain multiple projects and a project typically contains multiple items. These containers enable you to take advantage of the IDE in the following ways:

  • Manage settings for your solution as a whole or for individual projects.

  • Use Solution Explorer to handle the details of file management while you focus on items that make up your development effort.

  • Add items that are useful to multiple projects in the solution or to the solution without referencing the item in each project.

  • Work on miscellaneous files that are independent from solutions or projects.

Items: Files, References, Data Connections

Items can be files and other parts of your project such as references, data connections, or folders. In Solution Explorer, items can be organized in the following ways:

  • As project items, which are items that compose your project, such as forms, source files, and classes within a project in Solution Explorer. The organization and display depends on the project template you select as well as any modifications you make.

  • As solution items for files that are applicable to your solution as a whole in the Solution Items folder of Solution Explorer.

  • As miscellaneous files for files that are not associated with either a project or a solution and that can be displayed in a Miscellaneous Files folder.