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

Пример результатов выполнения

Enter number of employees: 210

Enter the name of the new employee: Hazem Abolrous

The employee information:

Employee number: 211

Employee name: Hazem Abolrous

Asymmetric Accessor Accessibility

The get and set portions of a property or indexer are called accessors. By default these accessors have the same visibility, or access level: that of the property or indexer to which they belong. For more information, see accessibility levels. However, it is sometimes useful to restrict access to one of these accessors. Typically, this involves restricting the accessibility of the set accessor, while keeping the get accessor publicly accessible. For example:

public string Name

{

get

{

return name;

}

protected set

{

name = value;

}

}

In this example, a property called Name defines a get and set accessor. The get accessor receives the accessibility level of the property itself, public in this case, while the set accessor is explicitly restricted by applying the protected access modifier to the accessor itself.

Restrictions on Access Modifiers on Accessors

Using the accessor modifiers on properties or indexers is subject to these conditions:

  • You cannot use accessor modifiers on an interface or an explicit interface member implementation.

  • You can use accessor modifiers only if the property or indexer has both set and get accessors. In this case, the modifier is permitted on one only of the two accessors.

  • If the property or indexer has an override modifier, the accessor modifier must match the accessor of the overridden accessor, if any.

  • The accessibility level on the accessor must be more restrictive than the accessibility level on the property or indexer itself.

Асимметричные методы доступа

Части свойства get и set или индексатора называются методами доступа. По умолчанию эти методы доступа обладают той же видимостью или уровнем доступа, присущим свойству или индексатору, которому они принадлежат. Однако иногда имеет смысл ограничить доступ к одному из этих методов доступа. Как правило, для этого ограничивается доступность метода доступа set и сохраняется открытая доступность метода доступа get. Пример.

-----

В этом примере свойство с именем Name определяет метод доступа get и set. Метод доступа get получает уровень доступности самого свойства – в этом случае это public, а метод доступа set ограничивается явным образом путем применения модификатора доступа protected к самому методу доступа.

Ограничения модификаторов доступа в методах доступа

Использование модификаторов доступа для свойств или индексаторов подчиняется следующим условиям:

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

  • Модификаторы доступа можно использовать только в том случае, если как свойство, так и индексатор имеют оба метода доступа set и get. В этом случае, модификатор разрешен в одном из двух методов доступа.

  • Если свойство или индексатор имеет модификатор override, модификатор доступа должен соответствовать методу доступа переопределенного метода доступа, если он существует.

  • Уровень доступности в методе доступа должен быть более ограничивающим, чем уровень доступности в самом свойстве или индексаторе.

Access Modifiers on Overriding Accessors

When you override a property or indexer, the overridden accessors must be accessible to the overriding code. Also, the accessibility level of both the property/indexer, and that of the accessors must match the corresponding overridden property/indexer and the accessors. For example:

public class Parent

{

public virtual int TestProperty

{

// Notice the accessor accessibility level.

protected set { }

// No access modifier is used here.

get {return 0;}

}

}

public class Kid : Parent

{

public override int TestProperty

{

// Use the same accessibility level as in the overridden accessor.

protected set { }

// Cannot use access modifier here.

get {return 0;}

}

}