Объявление и использование свойств чтения и записи 


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



ЗНАЕТЕ ЛИ ВЫ?

Объявление и использование свойств чтения и записи



Свойства обеспечивают удобную работу с открытыми членами данных без риска, с которым связан незащищенный, неконтролируемый и непроверяемый доступ к данным объекта. Это достигается с помощью методов доступа: особых методов, которые назначают и извлекают значения из базового члена данных. Метод доступа set обеспечивает назначение членов данных, а метод get извлекает значения членов данных.

В этом примере показан простой класс Person, имеющий два свойства: Name(string) и Age (int). Оба свойства предоставляют методы доступа get и set, поэтому они считаются свойствами чтения и записи.

Пример

ß-------


 

class TestPerson { static void Main() { // Create a new Person object: Person person = new Person(); // Print out the name and the age associated with the person: System.Console.WriteLine("Person details - {0}", person);   // Set some values on the person object: person.Name = "Joe"; person.Age = 99; System.Console.WriteLine("Person details - {0}", person);   // Increment the Age property: person.Age += 1; System.Console.WriteLine("Person details - {0}", person); } }
Person details - Name = N/A, Age = 0 Person details - Name = Joe, Age = 99 Person details - Name = Joe, Age = 100

Robust Programming

In the previous example, the Name and Age properties are public and include both a get and a set accessor. This allows any object to read and write these properties. It is sometimes desirable, however, to exclude one of the accessors. Omitting the set accessor, for example, makes the property read-only:

public string Name { get { return m_name; } }

 

ß------

 

 

Надежное программирование

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

public string Name { get { return m_name; } }

 


Alternatively, you can expose one accessor publicly but make the other private or protected. For more information, see Asymmetric Accessor Accessibility.

Once the properties are declared, they can be used as if they were fields of the class. This allows for a very natural syntax when both getting and setting the value of a property, as in the following statements:

person.Name = "Joe"; person.Age = 99;

Note that in a property set method a special value variable is available. This variable contains the value that the user specified, for example:

m_name = value;

Notice the clean syntax for incrementing the Age property on a Person object:

person.Age += 1;

If separate set and get methods were used to model properties, the equivalent code might look like this:

person.SetAge(person.GetAge() + 1);

The ToString method is overridden in this example:

public override string ToString() { return "Name = " + Name + ", Age = " + Age; }

Notice that ToString is not explicitly used in the program. It is invoked by default by the WriteLine calls.

 


Можно также сделать один метод доступа открытым, а другой — закрытым или защищенным. Дополнительные сведения см. в разделе Асимметричные методы доступа.

Объявленные свойства могут использоваться в качестве полей класса. Это приводит к более естественному синтаксису, где выполняется получение и установка значения свойства, как в следующих операторах.

person.Name = "Joe"; person.Age = 99;

Обратите внимание, что в свойстве метода set доступна особая переменная value. Эта переменная содержит значение, заданное пользователем, например:

m_name = value;

Обратите внимание на чистый синтаксис для увеличения значения свойства Age объекта Person.

person.Age += 1;

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

person.SetAge(person.GetAge() + 1);

В этом примере метод ToString переопределен.

public override string ToString() { return "Name = " + Name + ", Age = " + Age; }

Обратите внимание, что ToString не используется явно в программе. Он вызывается по умолчанию вызовами WriteLine.

 


Auto-Implemented Properties

Auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field can only be accessed through the property's get and set accessors.

Example

The following example shows a simple class that has some auto-implemented properties:

class LightweightCustomer { public double TotalPurchases { get; set; } public string Name { get; private set; } // read-only public int CustomerID { get; private set; } // read-only }

Auto-implemented properties must declare both a get and a set accessor. To create a readonly auto-implemented property, give it a private set accessor.

Attributes are not permitted on auto-implemented properties. If you must use an attribute on the backing field of a property, just create a regular property.

 



Поделиться:


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

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