Learn C # (Structure 2) a week

zhaozj2021-02-16  62

Search C # (Structure 2) C # Talent Bird (QQ: 249178521)

6. Instance field

· Example field ...

w Default Initialization is the default constructor that calls the compiler declaration.

w Must explicitly initialize in user-defined constructor

w can't initialize when they declare

Struct Pair

{

Public Pair (int x, int y)

{

THIS.X = X;

THIS.Y = Y; / / correct, all instance fields are explicitly initialized

}

...

Private int x, y; // Not initialized

}

The custom constructor of the structure must explicitly initialize all instance fields in the structure. (This is not this in the constructor of the class)

Public Badpair (int X, int y)

{

THIS.X = X; // Nothing this.y

}

Private int x, y;

The instance field of the structure can only be initialized in a constructor, and a method of assigning values ​​cannot be used. (This is not this in the constructor of the class)

Private int x;

Private int y = 0; // is illegal in the structure

7. 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

Struct 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

8. Read-only field

· Read-only field ...

w can't be assigned

W cannot be used as a Ref / OUT type parameter

Struct 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;

}

9. Term

· Two value types

w enumeration type

W structural type

· Two types of structural types

w Simple structural type

§ There is a keyword alias (such as System.Int32 == INT)

§ There are numerical expressions (for example, 42)

W user custom structural type

§ No keyword alias

§ No numerical expression

转载请注明原文地址:https://www.9cbs.com/read-22156.html

New Post(0)