This article is transferred from: http://m.biancheng.net/view/2807.html
After the class is defined in the C # language, the content contained in the class must be determined. The content contained in the class is called a member of the class.
The members in the class include fields, properties, and methods. Each class member needs to specify access modifiers and modifiers when it is defined.
There are two main access modifiers for a class, internal and public. If the access modifier is omitted, it is internal.
There are 4 access modifiers for members in the class, the specific usage is as follows.
1) public
Members can be accessed by any code.
2) private
Members can only be accessed by code in the same class. If no access modifiers are used before the class members, the default is private.
3) internal
Members can only be accessed by code in the same project.
4) protected
Members can only be accessed by code in the class or derived class. Derived classes are involved in inheritance and will be described in detail later.
The definition of the field is similar to the definition of the variable and constant introduced earlier, except that the access modifier and modifier can be added in front of the variable or constant.
Two modifiers are usually used to modify the field, namely readonly (read-only) and static (static).
Using readonly to modify a field means that you can only read the value of the field and not assign a value to the field.
The field decorated with static is a static field, which can be accessed directly by the class name.
Note that constants cannot be modified with static modifiers.
The syntax of the defined field is as follows.
Access modifier modifier data type field name;
Both access modifiers and modifiers can be omitted here, and the positions of access modifiers and modifiers can also be interchanged, but from a coding convention, access modifiers are usually placed before modifiers. In addition, the field names are unique when defining fields in the class.
[Example] Define fields using different modifiers in the Test class.
According to the title requirements, the code is as follows.
namespace code_1 { class Test { private int id; // Define private integer field id public readonly string name; // Define public read-only string type field name internal static int age; // Define internal static integer type Field age private const string major = "computer"; // Define private string type constant major } }
The above statement demonstrates the definition of different modifier fields, the key is to remember the use of these modifiers.
After the fields are defined in the class, when the class is loaded, the fields will be automatically assigned. The default values of the fields of different data types are different, as shown in the following table.
type of data | Defaults |
---|---|
Integer type | 0 |
Floating point | 0 |
String type | Null value |
Character | a |
Boolean | False |
Other reference types | Null value |