Search C # (class 2) C # Talent Bird (QQ: 249178521)
5. Instance field
· Example field ...
W is initialized to the default value (0 / false / null) in all constructor
w can explicitly initialize in a constructor
w can initialize when they declare
Sealed Class Pair
{
Public Pair (int x, int y)
{
THIS.X = X;
Y = Y;
}
...
Private int x;
Private int y = 42;
}
Memolive: The custom constructor in the structure must explicitly initialize all instance fields in the class. The instance field of the structure can only be initialized in a constructor, and a method of assigning values cannot be used.
The class is more convenient than the structure.
All fields in the class default to the default value.
In the constructor of the class, you can initialize when the field declaration.
In the above example, the parameter y of the constructor is assigned with the field y. The reason for the compiler is that the field Y has been assigned. In fact, if the field Y is not initialized, the compiler will still pass, and the sleepy field y has default 0, so there is no explicit initialization field Y in the constructor that does not have errors.
6. Static field
· Static field ...
W is initialized to 0 / False / Null by default
w can initialize at the time of declaration
w can only access the class name
Class Pair
{
Public Pair (int x, int y)
{
...
}
Private static pair origin = new pair (0, 0);
...
Private int x, y;
}
PAIR P = New Pair ();
...
Method (P.ORIGIN); / / Error, can only access class name
Method (Pair.origin); / / correct
Fields declared by Static modifiers are called static variables. When the class declares loading, the static variable begins to exist until the program ends.
The initial value of static variable:
l Integer variable is 0 (including enumeration)
l The real variable is 0.0
l BOOL type variable is false
l The reference variable is null
7. Read-only field
· Read-only field ...
w can't be assigned
W cannot be used as a Ref / OUT type parameter
Class Pair
{
Public Static Readonly Pair Origin = New Pair (0, 0);
Public Pair (int x, int y)
{
THIS.X = X;
THIS.Y = Y;
}
Public void reset ()
{
x = 0; // Error
Origin.x = 0; // Error
}
Private readonly int x, y;
}