In C #, we can access public fields very freely and without restrictions, but sometimes we may want:
(1) only values in a certain range can be assigned to a field;
(2) The field can only be read or written;
(3) other States of the object can be changed when the field is changed;
These fields alone cannot be used, so they have attributes.
The attribute contains two blocks: set and get. The set block is responsible for writing the attribute, and the get block is responsible for reading the attribute.
You can perform other operations in both blocks, such as verifying that the assigned value meets the requirements in set and determining whether to assign values.
There must be one attribute in the set and get blocks, because the attributes that cannot be read or written are meaningless.
The following is a simple example:
(1) attributes ensure security. When not used in this class, use Attribute names to avoid field names.
1 class MyClass2 {3 private string name;4 public string Name5 {6 get {return name;}7 set {name=value;}8 }9 }
(2) The set and get functions of the attribute can restrict some functions of the field for a certain purpose.
1 private int A = 0; 2 Public int A 3 {4 get {return this. a;} 5 set 6 {7 if (value> = 0 & value <= 100) 8 This. A = value; 9 else10 throw new exception ("the value range is invalid. "); 11} 12}
C # attributes