The comparison of fields and attributes in the middle and attributes: When will it be used?
When processing data in C#, a common problem is: when to use fields instead of attributes. This article aims to clearly explain the differences between fields and attributes, their own goals, and the most suitable application scenarios in each situation.
What is a field?Fields are a member of the class for direct storage of data. Fields are usually declared as private access modifiers to enforce the packaging and prevent direct access to the external class. Although fields can be accessed directly, they cannot perform any other tasks or verification.
What is the attribute?
On the contrary, attributes are a member, which disclose a method of interacting with the underlying field. The attribute allows you to read or write fields through the GET and SET access access method. This method provides a layer of abstraction and ensures that any data operation follows the established standards.When to use the field?
In the following circumstances, the field should be used:
You need to access the data directly and without restrictions, without any additional processing or verification.
You want to operate directly to other types of public fields. The data stored in the field is unchanged or unlikely to be changed frequently.
When to use the attribute?
You plan to modify the underlying field in the future version without affecting the external interface.
Example:
The above is the detailed content of Fields vs. Properties in C#: When Should I Use Which?. For more information, please follow other related articles on the PHP Chinese website!