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

Результат

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

В предыдущем пример можно использовать явную реализацию члена интерфейса с помощью полного имени члена интерфейса. Пример.

public string ISomeInterface.this

{

}

Однако, полное имя требуется для исключения неоднозначности только тогда, когда класс реализует более одного интерфейса с одинаковой сигнатурой индексатора. Например, если класс Employee реализует два интерфейса ICitizen и IEmployee с одинаковой подписью индексатора, требуется явная реализация члена интерфейса. Поэтому следующее объявление индексатора:

public string IEmployee.this

{

}

реализует индексатор для интерфейса IEmployee, а следующее объявление:

public string ICitizen.this

{

}

реализует индексатор для интерфейса ICitizen.

Comparison Between Properties and Indexers

Indexers are like properties. Except for the differences shown in the following table, all the rules that are defined for property accessors apply to indexer accessors also.

Property

Indexer

Allows methods to be called as if they were public data members.

Allows elements of an internal collection of an object to be accessed by using array notation on the object itself.

Accessed through a simple name.

Accessed through an index.

Can be a static or an instance member.

Must be an instance member.

A get accessor of a property has no parameters.

A get accessor of an indexer has the same formal parameter list as the indexer.

A set accessor of a property contains the implicit value parameter.

A set accessor of an indexer has the same formal parameter list as the indexer, and also to the value parameter.

Supports shortened syntax with Auto-Implemented Properties.

Does not support shortened syntax.

Сравнение свойств и индексаторов

Индексаторы подобны свойствам. За исключением различий, перечисленных в следующей таблице, все правила, определенные для методов доступа к свойствам, применимы и к методам доступа к индексаторам.

Свойство

Индексатор

Позволяет вызывать методы как открытые элементы данных.

Обеспечивает доступ к элементам внутренней коллекции объекта с помощью представления массива самого объекта.

Доступ посредством простого имени.

Доступ посредством индекса.

Допускаются статические члены или члены экземпляров.

Допускаются только члены экземпляров.

Метод доступа get свойства не имеет параметров.

Метод доступа get индексатора имеет такой же список формальных параметров, как и индексатор.

Метод доступа set свойства содержит неявный параметр value.

Метод доступа set индексатора имеет такой же список формальных параметров, как и индексатор, а также параметр value.

Поддерживается сокращенный синтаксис с Автоматически реализуемые свойства.

Не поддерживает сокращенный синтаксис

Delegates

A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be invoked like any other method, with parameters and a return value, as in this example:

public delegate int PerformCalculation(int x, int y);

Any method from any accessible class or struct that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. The method can be either static or an instance method. This makes it possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the signature of the delegate, you can assign your own delegated method.

Note:

In the context of method overloading, the signature of a method does not include the return value. But in the context of delegates, the signature does include the return value.

This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. For example, a sort algorithm could be passed a reference to the method that compares two objects. Separating the comparison code allows for the algorithm to be written in a more general way.

Delegates Overview

Delegates have the following properties:

  • Delegates are like C++ function pointers but are type safe.

  • Delegates allow methods to be passed as parameters.

  • Delegates can be used to define callback methods.

  • Delegates can be chained together; for example, multiple methods can be called on a single event.

  • Methods do not have to match the delegate signature exactly.

  • C# version 2.0 introduced the concept of Anonymous Methods, which allow code blocks to be passed as parameters in place of a separately defined method. C# 3.0 introduced lambda expressions as a more concise way of writing inline code blocks. Both anonymous methods and lambda expressions (in certain contexts) are compiled to delegate types. Together, these features are now known as anonymous functions.