Difference between attribute and field: difference between attribute Fields
From the declaration of the two, the public field is only a simple public variable exposed by the public modifier of the class.The attribute is the encapsulation of the field.It uses get and set accessors to control how to set or return field values.
BecauseThe essence of an attribute is a method (get or set method ),There is no attribute concept in IL. Therefore, for common assignment and value operations in the development process, using public variables is certainly faster than using attributes, and the performance is slightly higher (the speed of methods and variables is not required ).
Although a public field is fast, it must be open to public, so that the caller of the object can directly modify its value, whether the value content is legal, and whether an error occurs during running, without guarantee, the reusability of the class will be greatly reduced. On the contrary, attributes are similar to methods, which can process the values of the stored variables. If you think this value is invalid, you can perform local conversion or directly raise a warning. This provides great security for the use of such objects. During the running process, problems caused by incorrect public variable values will be greatly reduced.
From the above content, the two have their own advantages and disadvantages. In the actual project development process, which method do we choose to use?
If the following conditions are met, we can boldly use public fields:
1. Allow free read/write;
2. The value range is restricted only by the data type, but is not subject to any other restrictions;
3. Changes in values do not need to cause changes to any other member of the class;
The usage condition of the attribute is the opposite to that of the variable. If any of the following conditions is met, the attribute should be used:
1. Only the fields can be read or written;
2. You need to limit the value range of a field;
3. When changing the value of a field, you want to change other states of the object;
Summary: although public fields and attributes can be used under appropriate conditions during the development of the actual project, we should try our best to use the property ), instead of fields, set all fields as private fields. If you want to expose them, encapsulate them as attributes, which is recommended by Microsoft.
Http://www.cnblogs.com/netlyf/archive/2010/12/20/1910977.html