C # Introduction - Class and object, selected from "C # programming language detailed", give novice

xiaoxiao2021-03-06  40

Class (Class) is the most basic type in the C # type. Class is a data structure, combining status (fields) and behavior (methods, and other function members) in one unit. Class provides definitions for dynamically create class instances, that is, objects (Object). Inheritance and Polymorphism, that is, the mechanism of derived class can expand and specialize the base class.

Use class declarations to create new classes. Class declaration begins with a statement, its composition is as follows: First, the characteristics of the specified class and the name of the modifier, the name of the class, the base class (if any), and the interface name implemented by the class. The declaration head is the class, which consists of a group of members contained in braces ({}).

Below is a simple class named Point:

Public Class Point

{

Public Int x, y;

Public Point (int x, int y) {

THIS.X = X;

THIS.Y = Y;

}

}

Using the New operator creation class instance, it will assign memory for the new instance, call constructor initialization instance, and return to the reference to this instance. The following statement creates two Point objects and saves the references of those objects into two variables:

Point P1 = New Point (0, 0);

Point P2 = New Point (10, 20);

The memory occupied by the object will be automatically reclaimed when the object is no longer used. In C #, there is no need to explicitly release the object.

1.6.1 member

A member of the class or a static member, or an instance member (Instance MEMBER). Static members belong to class, instance members belong to objects (instances of classes).

Table 1.6 provides a description of the various members that can be included.

Table 1.6

The variable method of the constant value field class associated with the class is enabled by the calculation and behavior attributes performed by the class, enabling the object to read and write a naming attribute indexer that enables the object to index in the same manner as the array. The event can be generated by the unified notification operator class supported by the conversion and expression operator constructor initialization class or the behavior type of the class itself before permanently destroying the active behavior type is classified.

1.6.2 Accessibility

Each member of the class has an accessible accessibility that controls the program text area that can access the member. There are 5 possible accessible forms. Table 1.7 Outlines the visibility of the class.

Table 1.7 Accessibility

Accessibility PUBLIC Access Unrestricted Protected Access is limited to include classes or from type INTERNAL access to the class, INTERNAL access is limited to current assemblies protected, which is limited to the current assembly or type of private access from the class derived. class

1.6.3 base class

The statement of the class may specify a base class translation 4 by adding the name of the colon and the base class after class name. The base class is equivalent to derived directly from the Object class. In the example below, the base class of Point3D is Point, and the base class of Point is Object:

Public Class Point

{

Public Int x, y;

Public Point (int x, int y) {

THIS.X = X;

THIS.Y = Y;

}

}

Public Class Point3D: Point

{

Public int Z;

Public Point3d (int X, int y, int z): Point (x, y) {this.z = z;

}

}

The Point 3D class inherits the members of its base class. Inheritance means that the class will implicate all members of its base class (except for the constructor of the base class). Detective classes can add new members on the basis of inheritance base, but it cannot remove the definition of inherited members. In the previous example, the Point 3D class inherits the X field and the Y field from the Point class, and each Point3D instance contains three fields x, y, and z.

There is implicit conversion from the type type to its base class type. Also, the variables of the class type can reference the instance of this class, or any instance of the party. For example, for the previously given class declaration, the variable of the Point type can reference the Point instance or Point3D instance:

Point a = new point (10, 20);

Point B = New Point3D (10, 20, 30);

1.6.4 field

The field is a variable associated with an object or class.

When a field declaration contains a STATIC modifier, the field introduced by the declaration is a static field. It only identifies a storage location. No matter how many class instances have been created, the static fields will only have a copy.

When a field declaration does not contain a STATIC modifier, the field introduced by the declaration is an instance field. Each instance of the class contains a separate copy of all instance fields of the class.

In the following example, each instance of the Color class has a different copy of the R, G, B instance fields, but the static fields such as Black, White, Red, Green and Blue have only one copy:

Public Class Color

{

Public Static Readonly Color Black = New Color (0, 0, 0);

Public Static Readonly Color White = New Color (255, 255, 255);

Public Static Readonly Color Red = New Color (255, 0, 0);

Public Static Readonly Color Green = New Color (0, 255, 0);

Public Static Readonly Color Blue = New Color (0, 0, 255);

Private Byte R, G, B;

Public Color (byte R, byte g, byte b) {

THIS.R = R;

THIS.G = g;

THIS.B = B;

}

}

As shown in the example above, the read-only field is declared through the ReadOnly modifier. The assignment to the Readonly field can only appear as the component of the declaration, or appear in the instance constructor or static constructor in the same class.

1.6.5 method

Method is a member for implementing a computing or operation that can be performed by an object or class. Static Method can only be accessed by class. The instance method (INSTANCE METHOD) is to be accessed by an instance of the class.

The method has a parameter list (possibly empty), indicating the value or reference passed to the method; the method also has a return type (RETURN TYPE) to specify the type of value calculated and returned by the method. If the method does not return a value, its return type is VOID.

In the class of the declaration method, the signature of this method must be unique. The signature of the method consists of its name, parameter number, modifier and type of each parameter. The return type is not an integral part of the method signature. 1.6.5.1 parameters

The parameters are used to pass values ​​or reference variables to methods. When the method is called, the parameter translation of the method obtains the actual value from the specified argument. C # There are 4 parameters: value parameters, reference parameters, output parameters, and argument arrays.

Value parameter is used to enter the passage of the parameters. Value parameters are equivalent to a local variable, which is obtained from the auto-variable transferred from the parameter. Modifications to value parameters do not affect the transferred arguments.

Reference parameters (Reference Parameter) is used to input and output the pass parameters. The index quantity used to reference the parameters must be a variable, and during the method execution, the reference parameters and variables as the argument are the same storage location. The reference parameters are declared with the REF modifier. The following example shows the use of the REF parameter:

Using system;

Class test

{

Static Void Swap (Ref Int X, Ref Int Y) {

INT TEMP = X;

X = Y;

Y = TEMP;

}

Static void main () {

INT i = 1, J = 2;

SWAP (Ref I, REF J);

Console.writeline ("{0} {1}", I, j); // Output "2 1"

}

}

Output Parameter is used to output the pass parameter. The output parameter is similar to the reference parameters, and the difference is that the argument initial value provided by the caller is not critical. The output parameter is declared with an OUT modifier. The following example shows the use of the OUT parameter:

Using system;

Class test {

Static void Divide (int X, int y, out int result, out int remainder) {

Result = x / y;

Remainder = x% y;

}

Static void main () {

Int Res, REM;

Divide (10, 3, Out Res, Out Rem);

Console.writeline ("{0} {1}", res, trans); // output "3 1"

}

}

Parameter Array Allows the transmission of variable lengths to the method. The parameter array is declared with a Params modifier. Only the last parameters of the method can be declared as argument arrays, and it must be a one-dimensional array type. The WRITE and WRITELINE methods for the System.Console class are a good example of the parameter array application. The forms of declaration are as follows:

Public Class Console

{

Public Static Void Write (String FMT, params object [] args) {...}

Public Static void WriteLine (String FMT, params object [] args) {...}

...

}

When using the parameter array in the method, the parameter array behaves like a regular array type parameter. However, in the method call with array parameters, a single argument of parameter array types can be passed, or several independent variables of the element type of parameter arrays can be passed. For the latter case, the array instance will be automatically created and initialized by a given argument. Example:

Console.writeLine ("x = {0} y = {1} z = {2}", x, y, z);

Equivalent to the following statement:

Object [] args = new object [3];

Args [0] = x;

Args [1] = Y;

Args [2] = z;

Console.writeline ("x = {0} y = {1} z = {2}", args);

1.6.5.2 Method and local variable

Method specifies the statement to be executed when the method is called.

The method body can declare the variables specific to the method. Such variables are called local variables. Partial variable declaration specifies the type name, the variable name, may have an initial value. The following example declares a local variable I, which is 0; the other local variable j does not have an initial value.

Using system;

Class Squares

{

Static void main () {

INT i = 0;

Int J;

While (i <10) {

J = i * i;

Console.writeLine ("{0} x {0} = {1}", i, j);

i = i 1;

}

}

}

C # requires partial variables to explicitly assign a value before its value is obtained. For example, assume that the declaration of the previous variable I does not include an initial value, then the use of i will cause the compiler to report an error, the reason is that there is no clear assignment in the program.

The method can use the RETURN statement to return control to its caller. If the method is Void, the RETURN statement cannot specify an expression; if the method is non-VOID, the RETURN statement must contain an expression to calculate the return value.

1.6.5.3 Static method and example method

If a method declaration contains a STATIC modifier, the method is called static method. The static method does not operate a particular example and can only access static members.

If there is no STITIC modifier in a method statement, the method is called instance method. The instance method operates a particular instance, which is accessible to a static member, and an instance member can also be accessed. On the instance of the instance method, this instance can be accessed with this, and this is quoted in the static method is wrong.

The following Entity classes have two members of static and instance:

Class Entity

{

Static Int nextserialno;

Int serialno;

Public Entity () {

Serialno = NextSerialNo ;

}

Public int getSerialno () {

Return serialno;

}

Public static int getNextSerialNo () {

Return nextserialno;

}

Public static void setnextserialno (int value) {

Nextserialno = Value;

}

}

Each Entity instance contains a serial number (and some other information is omitted here). Entity Construction Functions (similar to instance methods) initialize new instances with the next valid serial number. Because the constructor is an instance member, it can access the Serialno instance field or access the nextserialno static field.

GetNextSerialno and SetNextSerialno static methods can access the nextserialno static field, but if the Access Serialno instance field will generate errors.

The following example shows the use of the Entity class: use system;

Class test

{

Static void main () {

Entity.setNextSerialno (1000);

Entity E1 = New Entity ();

Entity E2 = New Entity ();

Console.writeline (E1.GetSerialno ()); // Output "1000"

Console.writeline (E2.GetSerialno ()); // Output "1001"

Console.writeline (entity.getnextserialno ()); // Output "1002"

}

}

Note that setNextSerialno and GetNextSerialno static methods are called by class, while GetSerialno instance members are called by instances.

1.6.5.4 Virtual method, rewriting method and abstract method

If an example method contains a Virtual modifier, the method is called a virtual method. If there is no Virtual modifier, the method is called a nonvirtual method (Nonvirtual Method).

In a virtual method call, the runtime type of the instance involved in this call determines which implementation of the method to be called. In the non-virtual method call, the compile-time type "is a decisive factor.

The virtual method can be implemented by a derived class override. When an instance method declares contains an Override modifier, the method will rewrite the virtual method of the same signature inherited. The virtual method declaration is used to introduce a new method, while the rewriting method declares is used to dedicate existing inheritance virtual methods (by providing new implementation of this method).

Abstract (Abstract) method is a virtual method that is not implemented. The declaration of the abstract method is achieved by Abstract modifiers and only allows the use of abstract methods in abstract classes. Derivatives of non-abstract classes require overwriting abstract methods.

The following example declares an abstract class Expression that represents a node of an expression tree; it has three derived class constant, VariableReference, Operation, which implements constant, variable reference, and an expression tree node of the arithmetic operation.

Using system;

Using system.collections;

Public Abstract Class Expression

{

Public Abstract Double Evaluate (HashTable Vars);

}

Public Class Constant: EXPRESSION

{

Double Value;

Public constant (double value) {

THIS.VALUE = VALUE;

}

Public Override Double Evaluate (Hashtable Vars) {

Return Value;

}

}

Public Class VariableReference: Expression

{

String name;

Public variablereference (string name) {

THIS.NAME = Name;

}

Public Override Double Evaluate (Hashtable Vars) {

Object value = VARS [Name];

IF (value == null) {throw new Exception ("Unknown Variable:" Name);

}

Return Convert.TODOUBLE (VALUE);

}

}

Public Class Operation: Expression: EXPRESSION

{

Expression Left;

CHAR OP;

Expression Right;

Public Operation (Expression Left, CHAR OP, Expression Right) {

THIS.LEFT = LEFT;

THIS.OP = OP;

THIS.right = Right;

}

Public Override Double Evaluate (Hashtable Vars) {

Double x = left.evaluate (VARS);

Double y = right.evaluate (VARS);

Switch (OP) {

Case ' ': Return X Y;

Case '-': Return X - Y;

Case '*': return x * y;

Case '/': returnix x / y;

}

Throw New Exception ("Unknown Operator");

}

}

4 of the four classes for modeling arithmetic expressions. For example, using these classes, expression x 3 can be represented as the following form:

Expression E = New Operation

New variablereference ("x"),

' ',

NEW constant (3));

The Evaluate method of the Expression instance will be called to calculate the value of the expression, thereby generating a Double value. This method acquires HashTable as its own variable with a variable name (key) and value (input value). The Evaluate method is a virtual abstract method that means derived classes must override it and provide practical implementation.

The implementation of the EVALUATE method is just the constant returns a saved constant. VARIABLEREFERENCE is implemented in HashTable and returns the corresponding value. The implementation of Operation first calculates the value of left operating and right operation (by recursive call Evaluate method) and then performs a given arithmetic operation.

The following program uses the Expression class, calculates the expression x * (Y 2) for different X and Y values.

Using system;

Using system.collections;

Class test

{

Static void main () {

Expression E = New Operation

New variablereference ("x"),

'*',

New Operation

New variablereference ("y"),

' ',

NEW constant (2)

)

);

Hashtable vars = new hashtable ();

VARS ["X"] = 3;

VARS ["Y"] = 5;

Console.writeline (EVALUATE (VARS)); // Output "21"

Vars ["X"] = 1.5;

Vars ["y"] = 9; console.writeline (E.EVALUATE (VARS)); // Output "16.5"

}

}

1.6.5.5 method overload

Method Overloading allows the same name to declare multiple methods in the same class, and the conditions are the only signs. When compiling a calling method, the compiler uses the overload resolution to determine the method you should call. The overloaded decision finds the best matching from the variable, or reports an error message when the best match is found. The following example shows the heavy-duty decision work mechanism. Annotation in the MAIN method illustrates the method actually called.

Class test

{

STATIC void f () {

Console.writeline ("f ()");

}

Static void f (Object X) {

Console.writeline ("f (Object)");

}

Static void f (int x) {

Console.writeLine ("f (int));

}

Static void f (double x) {

Console.WriteLine ("DOUBLE)");

}

Static void f (double x, dpuble y) {

Console.WriteLine ("Double, Double));

}

Static void main () {

F (); // call f ()

F (1); // Call f (int)

F (1.0); // Call F (double)

F ("abc"); // Call F (Object)

F (Double) 1); // Call F (double)

F ((Object) 1); // Call F (Object)

F (1, 1); // Call F (Double, Double)

}

}

As shown in the above example, the specific method is always selected by the explicit type conversion of the argument to the parameter type.

1.6.6 other functions members

Function Member is a member of the executable statement. The method described in the previous section is the main function member. This section discusses the functions of several other C # support: constructor, attributes, indexers, events, operators, and destructors.

Table 1.8 shows a class named List that implements an extensible object list. This class contains examples of several all kinds of functions.

Table 1.8 Class Function Member Example

Public class list {const Int defaultcapacity = 4; constant Object [] items; int count; field

(Continued)

public List (): this (defaultCapacity) {} public List (int capacity) {items = new object [capacity];} Constructors public int Count {get {return count;}} public string Capacity {get {return items.Length } Set {if (value

C # supports both the instance constructor and also supports static constructors. The instance constructor is a member that implements the operation required for the initialization class instance. Static Constructor is a member for implementing the initialization class itself when loading the initialization class. The declaration of the constructor is like a method, but it does not return the type, and its name is the same as the class name containing it. If the Static modifier is included in the declaration of the constructor, it declares a static constructor, otherwise declares an instance constructor.

Example constructor can be overloaded. For example, List declares two instance constructors, one without parameters, one with an INT parameter. Use the New operator to call instance parameters. The following statement creates two List instances using the constructor of each List class.

List list1 = new list ();

List list2 = new list (10);

The instance constructor is different from other methods, which cannot be inherited. And, in addition to the instance constructor of your own declaration, it is impossible to have another example constructor. If a class does not declare any instance constructor, it will automatically provide a default empty instance constructor.

1.6.6.2 attribute

Property is the natural extension of the field, both of which have named members with associated types, and the syntax of the access field and attributes is the same. However, the attribute is different from the field, and does not represent a storage location. Instead, attribute has an Accessor, which specifies the statements that need to be executed when they are read or written.

The statement of the property is similar to the field, and the difference is that the attribute declaration ends with the GET Accessor and / or SET Accessor between delimiter {}, not a semicolon. At the same time, the attributes containing the GET Accessor and the SET Accessor are called read-write properties. Only the attribute of the GET Accessor is called read-only property. Only the attribute with the SET Accessor is called the write-only property.

The GET Accessor is equivalent to a parameterless method with the attribute type return value. In addition to the target of assignment, when references attributes in the expression, the GET accessor of this property is called to calculate the value of the property.

The SET Accessor is equivalent to a method with a single parameter that is Value and a non-return type. When an attribute is used as an assignment target, or when an operand as a or an operator is referenced, the SET Accessor will be called, and the transmitted argument will provide a new value.

The List class declares two attributes count and Capacity, which is only written and only written. Below is an example of using these properties:

List names = new list ();

Names.capacity = 100; // Call SET Accessor

INT i = names.count; // Call GET Accessor

INT j = names.capacity; // Call GET Accessor

Similar to the fields and methods, for example attributes and static properties, both of the C # are supported. Static attributes are static modifiers in the statement, while the instance properties are not.

The attribute accessor can be virtual. When Virtual, Abstract, Override modifiers are included in the property declaration, they will be used to attribute accessors.

1.6.6.3 indexer

The indexer is such a member: it enables an object to index in the same manner as an array. The declaration of the indexer is very similar, and the difference is that the name of the member is this, and the list of parameters later is between the delimiter ([]). The parameter is available in the accessor of the indexer. Similar to the properties, the indexer can be read or written, read, only written, and the accessor of the indexer can also be virtual. The List class declares a single read and write indexer and accepts an INT type parameter. The List instance may be indexed by an INT value by an indexer. E.g:

List names = new list ();

Names.Add ("liz");

Names.add ("martha");

Names.Add ("Beth");

For (int i = 0; i

String s = (string) Names [i];

Names [i] = S.toupper ();

}

Indexers can be overloaded, meaning that multiple indexers can be declared as long as their parameters or types are different.

1.6.6.4 incident

Event is a member that enables objects or classes to provide notification. The statement of the event is similar to the field, and the difference is that the event declaration contains an EVENT keyword, and the type of event declaration must be a delegate type.

In classes containing event declarations, events can be used like a field of delegate (such events cannot be Abstract, and the accessor cannot be declared). This field saves a commissioned reference, indicating that the event handler has been added to the event. This field is NULL if no event handler has not been added.

The List class declares a single event member named Changed, and the Changed event indicates that there is a new item to add to the event handler list, which is triggered by the onchanged virtual method. It first checks if the event is NULL (meaning without event handler). The notification of the incident is exactly equivalent to the delegate represented by the calling event - therefore do not require special language components to trigger an event.

The customer responds to the event through the event handler. Use the " =" operator to add or use "- =" to remove the event handler. The following example adds an event handler to the Changed event of the List class:

Using system;

Class test

{

Static int changeCount;

Static void ListChanged (Object Sender, Eventargs E) {

CHANGCOUNT ;

}

Static void main () {

List names = new list ();

Names.changed = New EventHandler (ListChanged);

Names.Add ("liz");

Names.add ("martha");

Names.Add ("Beth");

Console.writeLine (change); // Output "3"

}

}

For more advanced scene translation 8 for the underlying storage of the control event, the declaration of events can explicitly provide the Add and REMOVE accessor, which are similar to the SET accessor of the attribute.

1.6.6.5 operator

Operator is a function member that defines the meaning of a particular expression operator that can be applied to class instances. There are three operators that can be defined: one yuan operator, binary operator and conversion operator. All operators must be declared as public and static.

The List class declares two operators, operators "==" and operators "! =", And give new meanions to expressions, and these expressions apply these operators to the list instance. In particular, these operators define equal comparisons for two List objects, which is compared to their equals methods. The following example uses the "==" operator to compare two List instances. Using system;

Class test

{

Static void main () {

List a = new list ();

a.add (1);

A.Add (2);

List b = new list ();

B.Add (1);

B.Add (2);

Console.writeLine (a == b); // Output "True"

B.Add (3);

Console.writeLine (a == b); // Output "false"

}

}

The first console.writeLine output TRUE because two List collection objects contain objects that are both the number and values. If the list does not define the operator "==", the first console.writeline will output False because A and B reference different List instances.

1.6.6.6 destructor

The destructor is a member of the required operation required to implement the destructor instance. The destructor cannot with parameters and cannot have accessibility modifiers, and cannot be explicitly called. The destructor of the instance involved will automatically invoke the destruction function involved during garbage collection.

The garbage collector takes a relaxed strategy in deciding when to recover the object and the operational analytical function. It is particularly pointed out that the call timing of the destructuring function is uncertain, and the destructor may run on any thread. Due to these or other reasons, there is only no other possible solutions, and the class is intended to implement a destructive function.

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

New Post(0)