The difference between a property and a field
In C #, we have a very free, unrestricted access to public fields, but in some cases we may want to limit the values that can only be assigned to a field, or to require fields to be read-only or write-only, or to change some other state of an object when changing a field, which cannot be done by a single field. Then there is the attribute, which contains two blocks: Set and Get,set block are responsible for the writing of the property, the get block is responsible for the property read work. There are a few other things you can do in two blocks, such as verifying that the assigned value meets the requirements in set and deciding whether to assign a value. When one of the pieces is missing, the property is only readable or writable, and the properties in the set and get blocks must have one, because a property that cannot be read and cannot be written is meaningless.
Class MyClass
{
Private string name;
public string Name
{
get {return Name;}
set {Name=value;}
}
}
(1) Attributes are guaranteed to be secure, and when not used in this class, it is guaranteed that property names can be used to avoid
Use the name of the field.
(2) The set and get functions of a property can limit some of the functions of a field for some purpose.
Such as:
private int a=0;
public int a{Get{return THIS.A;} set {if (value >= 0 && value <=) This.a=value; else throw new Exception ("The range of values is not valid. "); }} (3) property does not have the ability to store data, the data exists in the field, so only modifying the field's data can change the data, modifying the value of the property is useless. Forwarding Address: http://www.cnblogs.com/yichengbo/archive/2011/07/31/2122916.html
Differences in properties and fields in C #