[Csharp]4 Package

Source: Internet
Author: User

New keyword

Use the New keyword to assign an object

Why use new to assign objects? After we assign a reference to an object by using the New keyword, the app will point to an example of a valid class in memory. The object must be allocated to memory using the New keyword, and if we do not use the new keyword, and try using a class variable in a subsequent code statement, you will receive an error from the compiler.


constructor function

The constructor never has a return value, even if it is void, and its name is always the same as the name of the class that needs to be constructed. Constructors can have multiple, and they differ from each other in the number and type of constructor arguments. Overloaded methods are used when we define methods that have the same name but differ in number and type of parameters.


this keyword

The This keyword can be used to resolve scope ambiguities that occur when the name of the passed parameter name and type data field are the same. If there is no ambiguity, you do not need to use the This keyword when the class accesses its own data or members. Another use of the This keyword is to design a class using a technique called a chain of constructors. A more concise solution would be to have a constructor that accepts the maximum number of arguments as a "main constructor" and implement the necessary validation logic.

The code is as follows:

Class Motorcycle

{

public int driveintensity;

public string DriveName;

Public motorcycle () {}

Public motorcycle (Int. intensity): This (intensity, "") {}

Public motorcycle (String name): This (0,name) {}

public motorcycle (int intensity,string name)

{

if (intensity>10)

{intensity=10; }

driveintensity=intensity;

Drivename=name;

}

.......

}


The logical flow of the constructor is as follows:

    1. Create an object by calling a constructor that has only a single int.
    2. The constructor forwards the supplied data to the main constructor and provides other initial parameters that the caller did not provide.
    3. The main constructor assigns the incoming data to the object's field data.
    4. Control returns to the constructor that was originally called, and executes all the remaining code statements.


Optional parameters

An example of a single constructor that uses optional parameters:

public motorcycle (int intensity=0,string name= "") {}


Static keyword

By using the static keyword to define many static members, these members can only be called directly from the class level, not the object reference. For example, System.Console, we did not call the WriteLine () method from the object level. In short, static methods are considered very common by (class designers) and do not require instances of the type to be created when members are called. Although any class can define static methods, they usually appear in the tool class. By definition, a tool class is a class that does not maintain any object-level state and is not created by the new keyword. Therefore, the tool class exposes all functionality at the class-level (that is, static) members. The static keyword can be used for: class data, class methods, class properties, constructors, entire class definitions.

Keep in mind that static data fields are shared by all objects.

It is also well suited to use static data if all objects of the same kind often use a value. Static constructors are special constructors and are ideal for initializing values of static data that are unknown at compile time (for example, we need to read from external files or generate random numbers, etc.).

    1. A class can only define a static constructor. This means that static constructors cannot be overloaded.
    2. The static constructor does not allow access modifiers and cannot accept any parameters.
    3. Static constructors are executed only once, regardless of how many types of objects are created.
    4. The runtime calls the static constructor before the runtime creates the class instance or the caller accesses the static member for the first time.
    5. The execution of a static constructor precedes any instance-level constructor.

If a class is defined as static, it cannot be created with the New keyword and can contain only the members or fields of the static keyword tag. (a class or struct that contains only static functionality is often referred to as a tool class)

C # access modifiers
Public
Type or type member
There are no restrictions on public items. Public members can be accessed from objects and from any derived class. Public types can be accessed from other external assemblies.
Private
Type member or nested type
Private items can only be accessed by the class (or structure) in which they are defined
Protected
Type member or nested type
Protected items can be used by the class in which they are defined and by any of its subclasses, but external classes cannot be accessed by the C # dot operator
Internal
Type or type member
An internal item can be accessed only in the current assembly. So, if we're in. NET class library, other assemblies cannot use them if they are defined by a set of internal types
protected internal
Type member or nested type If you combine the protected and internal keywords on an item, the items are available in the assemblies, classes, and derived classes that define them


Packaging Services for C #

Members that represent the state of an object should not be marked as public.

If you define class pay{... private int currpay; Pay the Pay=new Pay () in the out-of-class method; pay.currpay=10; causes a compiler error. If you want the external world to interact with private fields, the traditional approach is to define access methods (that is, get methods) and modify methods (that is, set methods).

Class pay

{

...

private int currpay;

public int Getpay ()

{

return currpay;

}

public int SetPay (string currpay)

{

Currpay=currpay;

}

...

}

But. NET language also advocates the use of attributes to force data to encapsulate state data. First, the understanding attribute is always mapped to the "actual" access method and the modification method. Therefore, the designer of a class can also execute any necessary internal logic before the value is assigned (for example, to capitalize the value, filter the illegal characters in the value, check the bounds of the numeric value, and so on). Like what:

Class Employee

{

private string EmpName;

public string Name

{

get {return empname; }

Set

{

if (value. LENGTH>15)

{Console.WriteLine ("error! Name must is less than characters! ");}

Else       

{empname=value; }

}

}

Note that the property specifies the type of data it encapsulates by the return value. And the attribute is defined without parentheses (or even empty parentheses). In the set scope of the property, we used the value tag, which is used to represent the values passed in when the property was set by the caller. The tag is not a true C # keyword, but a contextual keyword.


Automatic properties

While creating properties to encapsulate data, most C # properties include business logic in the set scope, but sometimes simply need to get and set values without implementing any logic. This means that you can end up with code such as the following:

public string Musicname

{

get {return musicname;}

set {Musicname=value;}

}

using automatic attribute syntax, you can quickly create this property. For example: public string Musicname {get; set;}

Unlike traditional C # properties, it is not allowed to build automatic attributes that are read-only or write-only, and must support both read and write capabilities.

First create the following class:

Class Car

{public string PetName {get; Set }

public int speed {get; set;}

public string Color {get; set;}

public void DisplayStats ()

{

Console.WriteLine ("Car name:{0}", PetName);

Console.WriteLine ("Speed:{0}", speed);

Console.WriteLine ("Color:{0}", Color);

}

}

Class Garage

{public int numberofcars {get; set;}

Public Car Myauto {get; set;}

}

Because C # provides default values for field data, you can know the value of Numberofcars (automatically set to 0), but when you call Myauto directly, you get a "null reference exception" at run time. This is because no new objects are set for the car member variables used in the background. Because the return field of a private field is created at compile time, you cannot use the field initialization syntax of C # to directly assign a reference type with the New keyword. This work must be performed inside the class constructor to ensure that the object is born in a safe manner. For example:

Class Garage

{public int numberofcars {get; set;}

Public Car Myauto {get; set;}

Public Garage ()

{

Myauto=new Car ();

Numberofcars=1;

}

Public Garage (Car car,int number)

{

Myauto=car;

Numberofcars=number;

}

}

Update, you can pass the car object to the garage object as follows:

Car c=new car ();

C.petname= "BMW";

c.speed=55;

C.color= "Red";

C.displaystats ();

Garage g=new Garage ();

G.myauto=c;

Console.WriteLine ("Number of Cars in Garage:{0}", G.numberofcars);

Console.WriteLine ("Your Car is named:{0}", G.myauto.petname);

}


Object initialization

Point Point =new Point {x=30,y=30};


Constant data

Public const double pi=3.14;

The constant field is implicitly static. You must specify an initial value for a constant when you define a constant.

Class Mymathclass

{Public const double PI;

Public Mymathclass ()

{pi=3.14; }

}

We will receive a compile-time error because the value of the constant must be known at compile time and the constructor is called at run time.


Read-only fields

Unlike static fields, read-only fields are not implicitly static. Therefore, if you want to expose pi from the class level, you must display the use of the static keyword.


Distribution type

Because field data, type properties, and constructors are seldom changed during the build process, methods need to be modified frequently.

For example:

In the Employee.cs file:

Partial class Employee

{

Method

Property

}

Employee.Internal.cs file:

Partial class Employee

{

field data

constructor function

}


Summary

The purpose of this chapter is to introduce the role of C # class types. We see that the class can accept any constructor to allow the object user to create the state when the object is created. Several class design techniques (and Related keywords) are also demonstrated in this chapter. Recall that the This keyword can be used to access the current object, the static keyword can be used to define fields and members at the class (not object) level, and the Const keyword (and the readonly modifier) can be used to define data points that will never change after the initial value is assigned.

[Csharp]4 Package

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.