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

Пример 2 Описание

В этом примере объявляется класс, в котором хранятся дни недели. Объявляется метод доступа get, который принимает строку (название дня недели) и возвращает соответствующее целое число. Например, воскресенье возвращает 0, понедельник возвращает 1 и т. д.

Код

-------

class Program

{

static void Main(string[] args)

{

DayCollection week = new DayCollection();

System.Console.WriteLine(week["Fri"]);

System.Console.WriteLine(week["Made-up Day"]);

}

}

Output

5

-1

Robust Programming

There are two main ways in which the security and reliability of indexers can be improved:

  • Be sure to incorporate some type of error-handling strategy to handle the chance of client code passing in an invalid index value. In the first example earlier in this topic, the TempRecord class provides a Length property that enables the client code to verify the input before passing it to the indexer. You can also put the error handling code inside the indexer itself. Be sure to document for users any exceptions that you throw inside an indexer accessor.

  • Set the accessibility of the get and set accessors to be as restrictive as is reasonable. This is important for the set accessor in particular.

------

Результат

5

-1

Надежное программирование

Существуют два основных способа повышения надежности и безопасности индексаторов.

  • Внедрите стратегию обработки ошибок на тот случай, если код клиента передаст недопустимое значение индекса. В первом примере, приведенном ранее в этом разделе, класс "TempRecord" предоставляет свойство "Length", позволяющее коду клиента проверить введенные данные перед тем, как передать их индексатору. Также можно поместить код обработки ошибки в индексатор. Задокументируйте для пользователей любые исключения, которые были созданы внутри метода доступа индексатора.

  • Установите максимальное обоснованное ограничение доступности для методов доступа get и set. Это особенно важно для метода доступа set. Дополнительные сведения см. в разделе Асимметричные методы доступа.

Indexers in Interfaces

Indexers can be declared on an interface. Accessors of interface indexers differ from the accessors of class indexers in the following ways:

  • Interface accessors do not use modifiers.

  • An interface accessor does not have a body.

Thus, the purpose of the accessor is to indicate whether the indexer is read-write, read-only, or write-only.

The following is an example of an interface indexer accessor:

public interface ISomeInterface

{

//...

// Indexer declaration:

string this[int index]

{

get;

set;

}

}

The signature of an indexer must differ from the signatures of all other indexers declared in the same interface.

Индексаторы в интерфейсах

Индексаторы можно объявлять в интерфейсах. Между методами доступа индексаторов интерфейса и методами доступа индексаторов класса существуют следующие отличия:

  • Методы доступа интерфейсов не используют модификаторы.

  • Метод доступа интерфейса не имеет тела.

Поэтому метод доступа предназначен для того, чтобы указывать, доступен ли индексатор для чтения и записи, только для чтения или только для записи.

Ниже приведен пример метода доступа индексатора интерфейса:

public interface ISomeInterface

{

//...

// Indexer declaration:

string this[int index]

{

get;

set;

}

}

Сигнатура индексатора должна отличаться от сигнатур всех других индексаторов, объявленных в том же интерфейсе.

Example

The following example shows how to implement interface indexers.

// Indexer on an interface:

public interface ISomeInterface

{

// Indexer declaration:

int this[int index]

{

get;

set;

}

}

// Implementing the interface.

class IndexerClass : ISomeInterface

{

private int[] arr = new int[100];

public int this[int index] // indexer declaration

{

get

{

// Check the index limits.

if (index < 0 || index >= 100)

{

return 0;

}

else

{

return arr[index];

}

}

set

{

if (!(index < 0 || index >= 100))

{

arr[index] = value;

}

}

}

}

Пример

В следующем примере показана реализация индексаторов интерфейса.

-----

class MainClass

{

static void Main()

{

IndexerClass test = new IndexerClass();

// Call the indexer to initialize the elements #2 and #5.

test[2] = 4;

test[5] = 32;

for (int i = 0; i <= 10; i++)

{

System.Console.WriteLine("Element #{0} = {1}", i, test[i]);

}

}

}

Output

Element #0 = 0 Element #1 = 0 Element #2 = 4 Element #3 = 0

Element #4 = 0 Element #5 = 32 Element #6 = 0 Element #7 = 0

Element #8 = 0 Element #9 = 0 Element #10 = 0

In the preceding example, you could use the explicit interface member implementation by using the fully qualified name of the interface member. For example:

public string ISomeInterface.this

{

}

However, the fully qualified name is only needed to avoid ambiguity when the class is implementing more than one interface with the same indexer signature. For example, if an Employee class is implementing two interfaces, ICitizen and IEmployee, and both interfaces have the same indexer signature, the explicit interface member implementation is necessary. That is, the following indexer declaration:

public string IEmployee.this

{

}

implements the indexer on the IEmployee interface, while the following declaration:

public string ICitizen.this

{

}

implements the indexer on the ICitizen interface.

------