logo
CSharp_Prog_Guide

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

-----