When we create the class, we usually use the property of the class, create the property we generally use the public modifier, the field is generally decorated with the private modifier, when using the property we pass the value is to modify the value of the field, rather than modify the value of the property (in the Get and set constructor), Changes in properties are caused by changes in the field to the constructor of the property.
Create a new person class and simply set a name property for the person class. As a rule, the first letter of the field is generally lowercase, the first letter of the property is capitalized, the assignment is called the contents of the set constructor, the corresponding value is to take the contents of the get constructor, of course, you can also add complex conditions in the set constructor. Value is the user input, and C # can be shortened by the get and set constructors, such as the following commented out code is the same as the above function.
1 Static voidMain (string[] args)2 {3 4Person person =NewPerson ();5Person. Name ="WHQ";//assignment operation in the set constructor, value is equivalent to the WHQ here6 Console.WriteLine (person. Name);7 console.readline ();8 }9 class PersonTen { One Private stringname; A Public stringName - { - Get{returnname;} the Set{name =value;} - } - //Public string Name - //{get; set;} +}
View Code
Results:
Fields and properties