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

Пример 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.

-----

Индексирование с использованием других значений

C# не ограничивает тип индексатора целочисленными типами. Например, может оказаться полезным использование в качестве индекса индексатора строки. Такой индексатор можно реализовать, выполнив поиск строки в коллекции и возвратив соответствующее значение. Методы доступа можно перегружать, версии типа "string" и "integer" могут сосуществовать.

Example 2

Description

In this example, a class is declared that stores the days of the week. A get accessor is declared that takes a string, the name of a day, and returns the corresponding integer. For example, Sunday will return 0, Monday will return 1, and so on.

Code

// Using a string as an indexer value

class DayCollection

{

string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };

// This method finds the day or returns -1

private int GetDay(string testDay)

{

int i = 0;

foreach (string day in days)

{

if (day == testDay)

{

return i;

}

i++;

}

return -1;

}

// The get accessor returns an integer for a given string

public int this[string day]

{

get

{

return (GetDay(day));

}

}

}