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


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

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



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

Если модификатор доступа в методе доступа не используется, домен доступности метода доступа определяется уровнем доступности свойства или индексатора.

Пример

В следующем примере содержатся три класса: BaseClass, DerivedClass и MainClass. В BaseClass, Name и Id для обоих классов имеется два свойства. Пример демонстрирует, как свойство Id в DerivedClass можно скрыть при помощи свойства Id в BaseClass, если используется ограничивающий модификатор доступа, такой как protected или private. Таким образом, при присвоении значений этому свойству, вместо этого вызывается свойство BaseClass. Замена модификатора доступа модификатором public сделает свойство доступным.

Пример также демонстрирует, что ограничивающий модификатор доступа, такой как private или protected, в методе доступа set свойства Name в DerivedClass запрещает доступ к методу доступа и создает ошибку при его присвоении.

ß----


 

public class DerivedClass: BaseClass

{

private string name = "Name-DerivedClass";

private string id = "ID-DerivedClass";

new public string Name

{

Get

{

return name;

}

// Using "protected" would make the set accessor not accessible.

Set

{

name = value;

}

}

// Using private on the following property hides it in the Main Class.

// Any assignment to the property will use Id in BaseClass.

new private string Id

{

Get

{

return id;

}

Set

{

id = value;

}

}

}

 

class MainClass

{

static void Main()

{

BaseClass b1 = new BaseClass();

DerivedClass d1 = new DerivedClass();

b1.Name = "Mary";

d1.Name = "John";

b1.Id = "Mary123";

d1.Id = "John123"; // The BaseClass.Id property is called.

System.Console.WriteLine("Base: {0}, {1}", b1.Name, b1.Id);

System.Console.WriteLine("Derived: {0}, {1}", d1.Name, d1.Id);

}

}


 

ß-----


Output

Name and ID in the base class: Name-BaseClass, ID-BaseClass

Name and ID in the derived class: John, ID-BaseClass

Comments

Notice that if you replace the declaration new private string Id by new public string Id, you get the output:

Name and ID in the base class: Name-BaseClass, ID-BaseClass

Name and ID in the derived class: John, John123

 


Результат

Name and ID in the base class: Name-BaseClass, ID-BaseClass

Name and ID in the derived class: John, ID-BaseClass

Примечания

Обратите внимание, что при замене объявления new private string Id new public string Id, результат будет следующим:

Name and ID in the base class: Name-BaseClass, ID-BaseClass

Name and ID in the derived class: John, John123

 


How to: Declare and Use Read/Write Properties

Properties provide the convenience of public data members without the risks that come with unprotected, uncontrolled, and unverified access to an object's data. This is accomplished through accessors: special methods that assign and retrieve values from the underlying data member. The set accessor enables data members to be assigned, and the get accessor retrieves data member values.

This sample shows a Person class that has two properties: Name (string) and Age (int). Both properties provide get and set accessors, so they are considered read/write properties.

Example

class Person { private string m_name = "N/A"; private int m_Age = 0; // Declare a Name property of type string: public string Name { get { return m_name; } set { m_name = value; } } // Declare an Age property of type int: public int Age { get { return m_Age; } set { m_Age = value; } } public override string ToString() { return "Name = " + Name + ", Age = " + Age; } }

 



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 81; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.147.89.24 (0.006 с.)