Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать
class Person
{

CHAPTER 6 MORE ABOUT CLASSES

Access Modifiers on Accessors

In this chapter, you’ve seen two types of function members that have get and set accessors: properties and indexers. By default, both a member’s accessors have the same access level as the member itself. That is, if a property has an access level of public, then both its accessors have that same access level. The same is true of indexers.

You can, however, assign different access levels to the two accessors. For example, the following code shows a common and important paradigm of declaring a private set accessor and a public get accessor. The get is public because the access level of the property is public.

Notice in this code that although the property can be read from outside the class, it can only be set from inside the class itself, in this case by the constructor. This is an important tool for encapsulation.

public string Name { get; private set; } public Person( string name )

{

Name = name;

}

}

class Program

{

static public void Main( )

{

Person p = new Person( "Capt. Ernest Evans" ); Console.WriteLine( "Person's name is {0}", p.Name );

}

}

There are several restrictions on the access modifiers of accessors. The most important ones are the following:

An accessor can have an access modifier only if the member (property or indexer) has both a get accessor and a set accessor.

Although both accessors must be present, only one of them can have an access modifier.

The access modifier of the accessor must be strictly more restrictive than the access level of the member.

Figure 6-20 shows the hierarchy of access levels. The access level of an accessor must be strictly lower in the chart than the access level of the member.

For example, if a property has an access level of public, you can give any of the four lower access levels on the chart to one of the accessors. But if the property has an access level of protected, the only access modifier you can use on one of the accessors is private.

156

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]