Define encapsulated class type Notes

Source: Internet
Author: User

As soon as you define a custom constructor, the default constructor is silently removed from the class and is no longer available!

Therefore, if you wish to allow the object user to create an instance of your type with the default constructor, as well as your custom constructor, you must explicitly redefine the default.

Once a custom constructor is defined, the default constructor is automatically removed from the class and no longer valid!

Therefore, if you want the object user to use the default constructor and user-defined constructor to create a type instance, you must re-define the default constructor.

 

Note it is a compiler error to use the this keyword within the implementation of a static member. as you will see, static members operate on the class (not object) level, and therefore at the class level, there is no current object (thus no this )!

This indicates that a compilation error occurs when this keyword is used in the implementation of static methods. We know that static members act at the class (rather than the object) level, so there is no current object at the class level (that is, there is no this )!

 

Chaining constructor callusing this

Class  Motorcycle {  Public   Int  Driverintensity;  Public   String  Drivername;  //  Constructor chaining.      Public  Motorcycle (){}  Public Motorcycle ( Int  Intensity ): This (Intensity, ""  ){}  Public Motorcycle ( String  Name ):  This ( 0  , Name ){}  //  This is the 'master' constructor that does all the real work.      Public Motorcycle ( Int Intensity, String Name ){  If (Intensity> 10  ) {Intensity = 10  ;} Driverintensity = Intensity; drivername = Name ;}...} 

Using this technique you can simplify your programming tasks, as the real work is delegated to a single Constructor (typically the constructor that has the most parameters ), while the other constructors simply "pass the buck."

Use this to call the series Constructor

 Class Motorcycle {  Public   Int  Driverintensity;  Public   String  Drivername;  //  Constructor chain      Public  Motorcycle (){}  Public Motorcycle ( Int  Intensity ):  This (Intensity,""  ){}  Public Motorcycle ( String  Name ):  This ( 0  , Name ){}  //  This is the "Main" constructor for all work.      Public Motorcycle ( Int Intensity, String  Name ){  If (Intensity> 10  ) {Intensity = 10  ;} Driverintensity = Intensity; drivername = Name ;}...} 

Using this technology can simplify programming tasks, because the real work is done by a constructor (usually this constructor has a majority of parameters, other constructor functions only play the ball (shirking responsibility ).

 

 
//Make a motorcycle.Motorcycle c =NewMotorcycle (5);

As you can see, the flow of constructor logic is as follows:

• We create our object by invoking the constructor requiring a single Int.

• This constructor forwards the supplied data to the master constructor and provides any additional startup arguments not specified by the caller.

• The Master constructor assigns the incoming data to the object's field data.

• Control is returned to the constructor originally called, and executes any remaining code statements.

 
//Create motorcycle.Motorcycle c =NewMotorcycle (5);

We can see that the logic flow of the constructor is as follows:

    • Create an object by calling a constructor with only one int parameter.
    • The constructor forwards the provided data to the primary constructor and provides other initial parameters not provided by the caller.
    • The main constructor assigns the input data to the field data of the object.
    • Controls the constructors returned to the initial call and executes all the remainingCodeStatement.

 

What if the value for your static data needed to be obtained from a database or external file? For this very reason, C # allows you to define a static constructor:

 Class  Savingsaccount {  Public   Double  Currbalance;  Public   Static   Double  Currinterestrate;  Public Savingsaccount ( Double  Balance) {currbalance =Balance ;}  //  A static constructor.      Static  Savingsaccount () {console. writeline (  "  In static ctor!  "  ); Currinterestrate = 0.04  ;}...} 

Simply put, a static constructor is a special constructor that is an ideal place to initialize the values of static data when the value is not known at compile time (e.g ., you need to read in the value from an external file, generate a random number, etc .). here are a few points of interest regarding static constructors:

• A given class (or structure) may define only a single static constructor.

• A static constructor does not take an access modifier and cannot take any parameters.

• A static constructor executes exactly one time, regardless of how many objects of the type are created.

• The runtime invokes the static constructor when it creates an instance of the class or before accessing the first static member invoked by the caller.

• The static constructor executes before any instance-level constructors.

What if the static data value needs to be obtained from a database or an external file? For this special reason, C # allows us to define static constructors:

 Class  Savingsaccount {  Public   Double  Currbalance;  Public   Static   Double  Currinterestrate;  Public Savingsaccount ( Double  Balance) {currbalance = Balance ;}  // Static constructor.      Static  Savingsaccount () {console. writeline (  "  In static ctor!  "  ); Currinterestrate = 0.04  ;}...} 

In short, static constructor is a special constructor and is very suitable for initializing static data values unknown during compilation (for example, we need to read values from external files or generate random numbers ). Here are some interesting points about the static constructor:

    • A class (or structure) can only define one static constructor.
    • Static constructors do not allow access to modifiers and cannot accept any parameters.
    • No matter how many types of objects are created, the static constructor only runs once.
    • Before the Runtime Library creates a class instance or the caller accesses a static member for the first time, the Runtime Library calls a static constructor.
    • The execution of static constructor is prior to any instance-level constructor.

 

When a class has been defined as static, It is not creatable using the new keyword, and it can contain only members or fields marked with the static keyword.

If a class is defined as a static class, it cannot be created with the New Keyword and can only contain members or fields marked with the static keyword.

 

The default access Modifiers

By default, type members are implicitly private while types are implicitly internal. Thus, the following class definition is automatically set to internal, while the type's default constructor is automatically set to private:

 
//An internal class with a private default constructor.ClassRadio {Radio (){}}

Default access modifier

By default, type members are implicitly private, while types are implicitly internal. therefore, the following class definitions are automatically set to internal, and the default constructor of the type is automatically set to private.

//Internal class with private default constructor.ClassRadio {Radio (){}}

Nested types

 
Public ClassSportscar {//OK! Nested types can be marked private.Private EnumCarcolor {red, green, blue }}

Here, it is permissible to apply the private access modifier on the nested type. however, nonnested types (such as the sportscar) can only be defined with the public or internalmodifiers. therefore, the following class definition is illegal:

//Error! Nonnested types cannot be marked private!Private ClassSportscar {}

Nested type

 
Public ClassSportscar {//OK! The nested type can be marked as private.Private EnumCarcolor {red, green, blue }}

Here, we can apply the private access modifier on the nested type. however, non-nested types (such as sportscar) can only be defined using public or internal modifiers. therefore, the following class definitions are invalid:

//Error! Non-nested types cannot be marked as private!Private ClassSportscar {}

Constant fields of a class or structure are implicitly static.

Constant fields of a class or structure are implicitly static.

 

Regardless of where you define a constant piece of data, the one point to always remember is that the initial value assigned to the constant must be specified at the time you define the constant.

ClassMymathclass {//Try to set PI in ctor?Public Const DoublePi;PublicMymathclass (){//Error!Pi =3.14;}}

The reason for this restriction has to do with the fact the value of constant data must be known at compile time.

No matter where constants are defined, we need to remember that the initial value must be specified for constants when defining constants.

ClassMymathclass {//Try to set PI in the constructor?Public Const DoublePi;PublicMymathclass (){//Error!Pi =3.14;}}

This restriction is because the constant value must be known during compilation.

 

Understanding read-only fields

Read-Only Field

 

Like a constant, a read-only field cannot be changed after the initial assignment. however, unlike a constant, the value assigned to a read-only field can be determined at runtime, and therefore can legally be assigned within the scope of a constructor (but nowhere else ).

Similar to constants, read-only fields cannot be changed after an initial value is assigned. however, unlike constants, the value assigned to a read-only field can be determined at runtime. Therefore, it is valid to assign values in the constructor scope (not elsewhere ).

 

Unlike a constant field, read-only fields are not implicitly static. Thus, if you want to expose PI from the class level, you must explicitly make use of the static keyword.

Unlike constant fields, read-only fields are not implicitly static. Therefore, to publish Pi (a read-only field in this example) at the class level, you must use the static keyword.

 

Understanding partial types

The only requirement when defining partial types is that the type's name (employee in this case) is identical and defined within the same. Net namespace.

Classification

the only requirement for defining a partial category is that the class name (here it is the employee) must be consistent and defined in the same. Net namespace.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.