logo search
CSharp_Prog_Guide

Метод доступа set

Метод доступа set похож на метод, имеющий тип возвращаемого значения void. В нем используется неявный параметр value, тип которого соответствует типу свойства. В следующем примере метод доступа set добавляется в свойство Name:

class Person

{

private string name; // the name field

public string Name // the Name property

{

get

{

return name;

}

set

{

name = value;

}

}

}

Когда свойству присваивается значение, выполняется вызов метода доступа set с помощью аргумента, предоставляющего новое значение. Пример.

Person p1 = new Person();

p1.Name = "Joe"; // the set accessor is invoked here

System.Console.Write(p1.Name); // the get accessor is invoked here

Использование имени неявного параметра value для объявления локальной переменной в методе доступа set является ошибкой.

Remarks

Properties can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access the property. The get and set accessors for the same property may have different access modifiers. For example, the get may be public to allow read-only access from outside the type, and the set may be private or protected.

A property may be declared as a static property by using the static keyword. This makes the property available to callers at any time, even if no instance of the class exists.

A property may be marked as a virtual property by using the virtual keyword. This enables derived classes to override the property behavior by using the override keyword.

A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual. Lastly, a property can be declared abstract. This means that there is no implementation in the class, and derived classes must write their own implementation.

Note:

It is an error to use a virtual, abstract, or override modifier on an accessor of a static property.