Recommendation 91: Visible fields should be refactored to properties
The essential difference between a field and a property is that the property is a method.
View the following person type:
class person { publicstringgetset;} }
After the compiler compiles, a private field and two public methods are actually generated for the property name:
[compilergenerated] Private string <Name>K__backingfield; [Compilergenerated] Public void set_name (string value) { this. <name>k__backingfield= value ;} [Compilergenerated] Public string get_name () { returnthis .<name>K__backingfield;}
As you can see, the property is actually the syntax sugar that the compiler gives us.
Attributes have the following advantages over fields:
1) You can add code to the property. Because properties are methods, you can have more granular control over the process of setting or getting properties within a method. such as: Add namechanged events for attributes, etc. The single field is not capable of accomplishing such a function.
2) allows properties to support thread safety. To make a property thread-safe, the type itself can be implemented. In order for a field to support thread safety, it can only be done by the caller itself.
3) The property is supported by the VS compiler, and it also has the ability to implement automatic attributes. The features of automatic attributes are widely used in LINQ, especially in anonymous classes, which can only implement read-only automatic attributes, not fields.
4) from a design perspective, the object-oriented perspective, the exposed fields should also use attributes. Changes the state of the field, the type is not notified, and the value of the property is changed, and type support is notified.
In summary, if a type has a visible field, then he should be refactored into a property. Of course, a field is recommended if a property is only visible to the interior and not to the above 4-point content.
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--Recommendation 91: Visible fields should be refactored to properties