Search C # (class three) C # (QQ: 249178521)
8. Constant field
· Constant field ...
W is implied to static
W must initialize during declaration
w Must be initialized to compile the constant value
W is only simple type, enumeration, string can be constant
Class Pair
{
Public Pair (int x, int y)
{
//???
}
...
Private const INT x = 0, y = 0;
}
In C #, the constant field is implied to Static, but you can't explicitly declare a constant field is static:
Static const INT x = 0; // Error
Constants must be initialized and can only initialize when declaring:
Const int x; // error
Constants must be initialized to compile time:
const Int x = method (); // Error
Only simple types, enumeration, strings can be declared as constant:
Const Pair P = New Pair (); // Error
9. Static constructor
· Static constructor initialization class
w can initialize the Static field instead of the const field
W When class is loaded, it is called by .NET call
w can't be called: no parameters, no access to the modifier
Class Pair
{
Public Static Readonly Pair Origin
Public Pair (int x, int y)
{
THIS.X = X;
THIS.Y = Y;
}
Static Pair ()
{
Origin = new pair (0, 0);
}
Private int x, y;
}
The static constructor can only be called by .NET, not by programmers. This guarantees that it will be called, only called once, and is called at the appropriate time (before any class or class is used). Since the programmer cannot call the static constructor, the static constructor has no parameters. For the same reason, the static constructor cannot have access to the modifier.
Static constructor cannot be used to initialize a constant field, even if the constant field is implicitly static. Because of the previous speech, the constant field must be initialized, and can only be initialized when it declares.