Общие сведения об индексаторах 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

Общие сведения об индексаторах



· Индексаторы позволяют индексировать объекты аналогично массивам.

· Метод доступа get возвращает значение. Метод доступа set присваивает значение.

· Ключевое слово this используется для определения индексаторов.

· Ключевое слово value используется для определения значения, присваиваемого методом set индексатора.

· Индексаторы не должны использовать в качестве индекса целочисленное значение; конкретный механизм поиска определяет разработчик.

· Индексаторы можно перегружать.

· Индексаторы могут иметь более одного формального параметра, например при доступе к двухмерному массиву.

 


Using Indexers

Indexers are a syntactic convenience that enable you to create a class, struct, or interface that client applications can access just as an array. Indexers are most frequently implemented in types whose primary purpose is to encapsulate an internal collection or array. For example, suppose you have a class named TempRecord that represents the temperature in Farenheit as recorded at 10 different times during a 24 hour period. The class contains an array named "temps" of type float to represent the temperatures, and a DateTime that represents the date the temperatures were recorded. By implementing an indexer in this class, clients can access the temperatures in a TempRecord instance as float temp = tr[4] instead of as float temp = tr.temps[4]. The indexer notation not only simplifies the syntax for client applications; it also makes the class and its purpose more intuitive for other developers to understand.

To declare an indexer on a class or struct, use the this keyword, as in this example:

public int this[int index] // Indexer declaration { // get and set accessors }

Remarks

The type of an indexer and the type of its parameters must be at least as accessible as the indexer itself.

The signature of an indexer consists of the number and types of its formal parameters. It does not include the indexer type or the names of the formal parameters. If you declare more than one indexer in the same class, they must have different signatures.

An indexer value is not classified as a variable; therefore, you cannot pass an indexer value as a ref or out parameter.

To provide the indexer with a name that other languages can use, use a name attribute in the declaration. For example:

[System.Runtime.CompilerServices.IndexerName("TheItem")] public int this [int index] // Indexer declaration { }

This indexer will have the name TheItem. Not providing the name attribute would make Item the default name.


Использование индексаторов

Индексаторы являются синтаксическим удобством, позволяющим создавать класс, структуру или интерфейс, доступ к которому клиентские приложения получают, как к массиву. Чаще всего индексаторы реализуются в типах, главная цель которых — инкапсуляция внутренней коллекции или массива. Например, предположим, что имеется класс с именем "TempRecord", представляющий набор температур по шкале Фаренгейта, полученных в 10 различных моментов в течение 24 часов. Класс содержит массив с именем "temps" типа "float", представляющий температуры, и DateTime, представляющий дату регистрации температур. Путем внедрения в этот класс индексатора клиенты получат доступ к температурам в экземпляре TempRecord с помощью float temp = tr[4], а не float temp = tr.temps[4]. Использование индексатора не только упрощает синтаксис для клиентских приложений, но и делает класс и его назначение интуитивно понятными для других разработчиков.

Чтобы объявить индексатор для класса или структуры, используйте ключевое слово this как показано в следующем примере:

ß----

Заметки

Тип индексатора и типы его параметров должны иметь по крайней мере такой же уровень доступности, как и сам индексатор. Дополнительные сведения об уровнях доступности см. в разделе Модификаторы доступа.

Дополнительные сведения об использовании индексаторов с интерфейсом см. в разделе Индексаторы интерфейсов.

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

Значение индексатора не классифицируется как переменная, поэтому не допускается передача значения индексатора как параметра ref или out.

Чтобы предоставить индексатору имя, которое можно использовать в других языках, используйте в объявлении атрибут name. Пример.

ß----

Этот индексатор будет иметь имя TheItem. Если атрибут имени не предоставлен, используется имя по умолчанию Item.

 


Example 1

Description

The following example shows how to declare a private array field, temps, and an indexer. The indexer enables direct access to the instance tempRecord[i]. The alternative to using the indexer is to declare the array as a public member and access its members, tempRecord.temps[i], directly.

Notice that when an indexer's access is evaluated, for example, in a Console.Write statement, the get accessor is invoked. Therefore, if no get accessor exists, a compile-time error occurs.

Code

class TempRecord { // Array of temperature values private float[] temps = new float[10] { 56.2F, 56.7F, 56.5F, 56.9F, 58.8F, 61.3F, 65.9F, 62.1F, 59.2F, 57.5F }; // Auto-Implemented Property System.DateTime date { get; set; } // To enable client code to validate input // when accessing your indexer. public int Length { get { return temps.Length; } } // Indexer declaration. // Input parameter is validated by client // code before being passed to the indexer. public float this[int index] { get { return temps[index]; }   set { temps[index] = value; } } }

Пример 1

Описание

В следующем примере показано, как объявить закрытое поле массива temps и индексатор. Индексатор обеспечивает прямой доступ к экземпляру tempRecord[i]. В качестве альтернативы применению индексатора можно объявить массив как член типа public осуществлять прямой доступ к его членам tempRecord.temps[i].

Обратите внимание, что при вычислении доступа индексатора, например, в инструкции Console.Write вызывается метод доступа get. Таким образом, если не существует метода доступа get, происходит ошибка времени компиляции.

Код

ß----


 

class MainClass { static void Main() { TempRecord tempRecord = new TempRecord(); // Use the indexer's set accessor tempRecord[3] = 58.3F; tempRecord[5] = 60.1F;   // Use the indexer's get accessor for (int i = 0; i < 10; i++) { // This example validates the input on the client side. You may // choose to validate it in the class that implements the indexer, and throw an // exception or return an error code in the case of invalid input. if (i < tempRecord.Length) { System.Console.WriteLine("Element #{0} = {1}", i, tempRecord[i]); } else { System.Console.WriteLine("Index value of {0} is out of range", i); } }   //Uncomment this code to see how the.NET Framework handles indexer exceptions //try //{ // System.Console.WriteLine("Element #{0} = {1}", tempRecord[tempRecord.Length]); //} //catch (System.ArgumentOutOfRangeException e) //{ // System.Console.WriteLine(e); //} } }

Indexing Using Other Values

C# does not limit the index type to integer. For example, it may be useful to use a string with an indexer. Such an indexer might be implemented by searching for the string in the collection, and returning the appropriate value. As accessors can be overloaded, the string and integer versions can co-exist.


 

ß-----

 

 



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 123; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.12.155.100 (0.009 с.)