Types of different classes in C #

Source: Internet
Author: User

A class is a custom type consisting of field data (member variables) and members (attributes, methods, constructors, events, and so on) operating field data. Field data indicates the status of the class instance (object.

In C #, classes are defined using the class keyword, for example:

Public class Car {

// Car field (Status)

Private int _ speed;

Private string _ name;

// Attributes of the Car operation field

Public int Speed

{

Set {this. _ speed = value ;}

Get {return this. _ speed ;}

}

Public string Name

{

Set {this. _ name = value ;}

Get {return this. _ name ;}

}

// Explicitly define the default constructor

Public Car (){}

// Custom Constructor

Public Car (string name, int speed)

{

This. _ name = name;

This. _ speed = speed;

}

// Car function (method)

Public void ShowState ()

{Console. WriteLine ("Car {0} is going {1} MPH", this. _ name, this. _ speed );}}

In addition, fields of the class are rarely defined as public. To protect the integrity of state data, it is best to define the field data as private (or protected ), and then provide externally controlled access through properties.

Use the new Keyword to allocate objects.

The object must be allocated to the memory using the new keyword. If the new keyword is not used, and then the class variable is used, a compilation error is returned.

Public static void Main (string [] args ){

// Error. forget to use new

Car c;

C. Name = "Bruce ";}

Correct example:

Public static void Main (string [] args)

{

// Create a Car object.

Car c; // declares a reference to a Car object that has not been created.

C = new Car ("bruce wong", 150); // assign a valid reference to an object through new, which directs to a valid object in the memory.

C. ShowState ();

Console. ReadKey (true );}?

Class Constructor

Purpose: assign a value to the field (State) of the object, which allows you to create its state when creating the object.

Constructor is a special type of method that is called indirectly when an object is created using the new keyword.

Note: The constructor does not return values (even void). Its name is always the same as the class name.

Default constructor

C # provides a default constructor, which can be redefined if needed. The default constructor does not accept any parameters. It allocates new objects to the memory and ensures that all fields are set to the correct default value. If you are not satisfied with these default values, you can redefine the default constructor. For example:

Public Car (){

This. _ name = "My Car ";

This. _ speed= 100 ;}

Every time new Car () is used, a Car object in the status of _ name = "My Car" _ speed = 100 will be created.

Custom Constructor

Purpose: Initialize the object status when creating an object.

Public Car (string name, int speed)

{

This. _ name = name;

This. _ speed = speed;

}

Note: Once a custom function is defined, the built-in default constructor will be automatically removed from the class (the default constructor cannot be used to create objects ). If you want to use the default constructor to create class objects, you must explicitly define the default constructor.

The role of this keyword

1. Provide access to the current instance.

It can solve the Scope Ambiguity generated when both the name of the input parameter and the field name of the type are involved. For example:

Class Car {

Private string name;

Public void SetName (string name)

{This. name = name ;}}

The parameter name value is assigned to the name field of the object (Instance). this indicates the instance.

Ii. parameter transfer. Use this to call the series Constructor

Use a technology called constructor to design a class. This design pattern is useful when the class defines multiple constructors.

Since constructor usually checks input parameters to force various business rules, redundant verification logic is often found in the constructor set of classes.

Class Car {

Public int Speed {get; set ;}

Public string Name {get; set ;}

Public Car (){}

Public Car (int speed) {if (speed> 150) {speed = 150;} this. Speed = speed ;}

Public Car (string name) {this. Name = name ;}

Public Car (int speed, string name) {if (speed> 150) {speed = 150 ;}this. Speed = speed; this. Name = name ;}}

Series constructor solution: let a constructor that accepts the maximum number of parameters as the "Main constructor" and implement the necessary verification logic. Other constructors use the this keyword to forward parameters to the primary constructor and provide other required parameters. In this way, we only care about the logic of the main constructor, while other constructor bodies are basically empty.

Class Car {

Public int Speed {get; set ;}

Public string Name {get; set ;}

Public Car (){}

Public Car (int speed): this (speed ,""){}

Public Car (string name): this (0, name ){}

// Main constructor public Car (int speed, string name)

{

If (speed> 150) {speed = 150 ;}

This. Speed = speed;

This. Name = name;

}}

Using this keyword to concatenate constructor can simplify programming tasks and make class definitions easier to maintain and more concise. But it is not mandatory.

Execution sequence of series constructor:

1. Call the constructor to forward the parameter values provided by the caller to the primary constructor and provide other required initialization parameter values.

2. Execute the main constructor.

3. Execute the logic of calling the constructor body.

Iii. Custom Indexer

Class CarCollection: IEnumerable {

Private ArrayList arCar = new ArrayList ();

Public Car this [int index]

{

Get {return (Car) arCar [index];}

Set {arCar. Insert (index, value );}

}

//...}

Static keywords

C # classes (or structures) can use the static keyword to define many static members. These static members can only be called at the class level but not at the object level (you do not need to create instance objects when calling static members ).

For example:

// Error. WriteLine is a static member and a class-level method. Console c = new Console (); c. WriteLine ("Bruce Wong"); // correct! WriteLine is a Class-level method Console. WriteLine ("Bruce Wong ");

Note:

1. Static members can only operate static data or static members of call classes. Non-static members can operate on instance data and static data (members), because static members are available to all instances of the class.

2. CLR allocates static data to the memory only once. Changing static data will affect all such instances.

Define static Constructor

The constructor is used to set the data value of A Class Object when creating a class object. If you use an instance-level constructor to assign values to static data, you will be surprised to find that each time you create a class object, the static data will only be reset. Therefore, it is best to use a static constructor to initialize static data.

Static constructor is a special constructor, which is very suitable for initializing static data values unknown during compilation:

1. A Class (structure) can only define one static constructor.

2. The static constructor does not allow access to modifiers and does not accept any parameters.

3. The static function is executed once no matter how many class instances are created.

4. Before the CLR creates a class instance or calls a class static member for the first time, the CLR calls a static constructor.

5. The static constructor is executed before other constructor at the instance level.

Static class: If a class is defined as static (modified with the static keyword), you cannot use the new keyword to create a class instance, static classes can only contain static class members or fields marked with static.

PS: project application objects (such as classes defining the Main () method) are usually defined as static classes to ensure that only static members are included and cannot be directly created. For example:

Static class Program {

Static void Main (string [] args)

{

//...

}}

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.