Principle one: Always be able to use attributes instead of data Member that can be accessed directly
Always use the properties instead of accessible data members.
Why Use attributes:
The 1.Net data binding supports only the property, not the access of public data member
The purpose of the Data binding is to bind the property of an object to the control of a user interface, Web control, or Windows Form control. The Data binding is implemented through reflection,
The following example: TextBoxCity.DataBindings.Add ("Text", Address, "City");
This code is to bind the Text property of the textboxcity to the city property of the Address object.
If you change the address of the city to public data member, this code will not run.
2. When there are new requirements, it is much easier to adapt to this new requirement by modifying the property's implementation method than to modify all of the public data member in your program to accommodate this requirement.
For example, you have previously defined a class customer, now you find that because the original carelessness did not force the customer name can not be empty, if you use the property, you can easily add a check mechanism,
As in the following code:
1 Public classCustomer2 {3 Private stringname;4 Public stringName5 {6 Get7 {8 returnname;9 }Ten Set One { A if(Value = =NULL) || (value.) Length = =0)) { - Throw NewArgumentException ("Name can not is blank","Name"); - } theName =value; - } - } - //... +}View Code
If you use public data member, you'll need to look through your programs and modify them everywhere.
3.Property is implemented with methods, so it is very convenient to add multi-threaded support.
For example, to add support for synchronous access:
1 Public classCustomer2 {3 Private stringname;4 Public stringName5 { 6 Get 7 { 8 Lock( This) 9 { Ten returnname; One } A } - Set - { the Lock( This) - { -Name =value; - } + } - } +}View Code
4..Property is implemented with methods, so it has everything that methods has. The property can be defined as virtual:
You can also expand the property to abstract and even become part of the interface.
Summarize:
All in all, when you want your inner data to be accessed by outsiders (whether public or protected), be sure to use the property.
For sequences and dictionaries, use indexer. Your type of data member should always be private, no exception.
Using the property, you can get the following benefits:
1. Data Binding Support
2. More adaptable to changes in demand, more convenient way to modify the implementation
Remember, it takes more than 1 minutes to use the property, saving you n hours when you modify the program to fit the design changes.
Effective C # Learning notes (Principle one: always be able to use attributes instead of data Member that can be accessed directly)