Accessor Accessibility Domain



If you use an access modifier on the accessor, the accessibility domain of the accessor is determined by this modifier.

If you did not use an access modifier on the accessor, the accessibility domain of the accessor is determined by the accessibility level of the property or indexer.

Example

The following example contains three classes, BaseClass, DerivedClass, and MainClass. There are two properties on the BaseClass, Name and Id on both classes. The example demonstrates how the property Id on DerivedClass can be hidden by the property Id on BaseClass when you use a restrictive access modifier such as protected or private. Therefore, when you assign values to this property, the property on the BaseClass class is called instead. Replacing the access modifier by public will make the property accessible.

The example also demonstrates that a restrictive access modifier, such as private or protected, on the set accessor of the Name property in DerivedClass prevents access to the accessor and generates an error when you assign to it.

public class BaseClass { private string name = "Name-BaseClass"; private string id = "ID-BaseClass";   public string Name {    get { return name; }    set { } }   public string Id {    get { return id; }    set { } } }

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

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

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

Пример

В следующем примере содержатся три класса: 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; } }

 


Дата добавления: 2019-03-09; просмотров: 272; Мы поможем в написании вашей работы!

Поделиться с друзьями:






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