C # Fields, attributes, and member variables
Introduction:
C # these basic concepts are slightly different from those in java and C ++. The difference is summarized here because it is easy to confuse. Hope to help beginners!
1. Definitions and functions
1. field: defined at the class level of C #. It is at the same level as the method.
It is generally used for internal class access and acts as a "global variable" in a category. It can also be used with attributes.
2. attribute: It is also defined at the C # class level and is generally accessible to external classes.
3. member variables: "global variables". variables defined in the class are different from local variables defined in the method. It is not the same level as the field attribute. Fields and attributes can be called member variables.
Ii. Use
Class Basic
{
Private string FieldVar; // This is a field, called in the current class
Private string fieldVarForProperty; // This is a field, used together with the attribute
Public string FieldVarForProperty // This is an attribute
{
Get {return fieldVarForProperty;} // The field is used in the property.
Set {fieldVarForProperty = value ;}
}
}
Here we can see that the field is a variable, and the attribute is similar to the method. Attribute allows the external class to access the fields of the current class. There are some problems:
1. Some people say that we can define the field as public, so that external access will not be available.
Yes, but it violates the class design principles. Object-oriented data needs to be encapsulated. If the field is defined as public to allow external access, the field will be damaged at will. So do not do this
2. Why should attributes be used with fields?
Define it as follows.
Public string FieldProperty
{
Get {return FieldProperty ;}
Set {FieldProperty = value ;}
}
There is indeed no problem with compilation. However, when we call the get/set method, the FieldProperty attribute is used in the method body, which is an endless loop and the program will go down.
Note: C # has an automatically implemented attribute, that is
Public string FieldProperty
{
Get; set;
}
C # automatically declares a private field
Iii. Differences between fields and attributes
1. fields are always readable and writable (except for the readonly keyword). Attributes must be readable and writable (at least the same)
2. fields are always executed immediately, which is highly efficient. The attribute also needs to call methods, which is less efficient.
3. fields can be used as ref, out parameters, and attributes are not allowed