Introduction to C #-classes and objects

Source: Internet
Author: User
Tags abstract define arithmetic array empty expression garbage collection vars
The object class (Class) is the most basic type in a C # type. A class is a data structure that combines states (fields) and behaviors (methods and other function members) in a single unit. class provides a definition for dynamically creating an instance of a class, that is, an object. Classes support Inheritance (inheritance) and polymorphism (polymorphism), which is the mechanism by which derived classes can extend and specialize base classes.

You can create a new class by using a class declaration. A class declaration begins with a declaration header, which is comprised of the first specifying the attributes and modifiers of the class, followed by the name of the class, the name of the base class (if any), and the name of the interface implemented by the class. The declaration header is followed by a class body, which consists of a set of member declarations contained in braces ({}).

The following is a declaration of a simple class named point:

public class Point

{

public int x, y;



public point (int x, int y) {

this.x = x;

This.y = y;

}

}

Use the new operator to create an instance of a class that allocates memory for the new instance, calls the constructor to initialize the instance, and returns a reference to the instance. The following statement creates two point objects and saves references to those objects in two variables:

Point P1 = new Point (0, 0);

Point P2 = new Point (10, 20);

When an object is no longer used, the memory of the object is automatically recycled. In C #, it is not necessary and impossible to explicitly dispose of objects.

1.6.1 Members
The member of the class is either a static member or a member of the instance (instance). A static member belongs to a class, and an instance member belongs to an object (an instance of a class).

Table 1.6 Provides a description of the various members that the class can contain.

Table 1.6 members of class

Members
Description

Constant
Constant value associated with the class

Field
The variables of the class

Method
Computation and behavior that can be performed by class

Property
Enables objects to read and write named properties of a class

Indexing device
Enables an object to be indexed in the same way as an array

Event
Notifications that can be generated by class

Operator
Transformations and expression operators supported by a class

Constructors
Initializes an instance of the class or the class itself

destructor
Behavior that is performed before an instance of a class is permanently destroyed

Type
Nested types declared by the class


1.6.2 Accessibility
Each member of a class has an associated accessibility that controls the range of program text that can access that member. There are 5 possible forms of accessibility. Table 1.7 outlines the meaning of the accessibility of the class.

Table 1.7 Accessibility of classes

Accessibility
Significance

Public
Access not restricted

Protected
Access is limited to the containing class or types derived from the containing class

Internal
Access is limited to the current assembly

protected internal
Access is limited to the current assembly or type derived from the containing class

Private
Access is limited to the containing class


1.6.3 base class
The declaration of a class may specify a base class of 4 by adding the name of the colon and base class after the class name. Omitting a base class is equivalent to deriving directly from the object class. In the following example, the base class for Point3D is point, and the base class for 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 Point3D class inherits the members of its base class. Inheritance means that a class implicitly contains all the members of its base class (in addition to the constructor of the base class). A derived class can add new members on the basis of inheriting a base class, but it cannot remove the definition of an inherited member. In the preceding example, the Point3D class inherits the X and Y fields from the point class, and each Point3D instance contains three fields X,y and Z.

There is an implicit conversion from the class type to any of its base class types. Also, a variable of a class type can reference an instance of that class, or any instance of a derived class. For example, for the class declaration given earlier, a variable of point type can refer to the point instance or Point3D instance:

Point A = new Point (10, 20);

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

1.6.4 fields
A field is a variable that is associated with an object or class.

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

When a field declaration does not contain a static modifier, the field introduced by the declaration is an instance field (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 a color class has a different copy of the R,g,b instance field, but there is only one copy of static fields such as Black,white,red,green and blue:

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 previous example, the read-only field is declared with the ReadOnly modifier. An assignment to a readonly field can occur only as part of a declaration, or in an instance constructor or static constructor in the same class.

1.6.5 method
A method is a member that implements a calculation or operation that can be performed by an object or class. Static methods can only be accessed through classes. Instance methods (instance method) are accessed through instances of the class.

Method has a list of parameters (possibly empty) that represents the value or reference that is passed to the method, and the return type of the method that specifies the type of the value that is evaluated and returned by the method parameter. If the method does not return a value, its return type is void.

In a class that declares a method, the signature of the method must be unique. The signature of a method consists of its name, the number of parameters, the modifiers and types of each parameter. The return type is not part of the method signature.

1.6.5.1 parameters
parameter is used to pass a value or reference variable to a method. When a method is invoked, the parameter of the method 5 obtains their actual value from the specified argument (argument). C # has 4 parameters: A value parameter, a reference parameter, an output parameter, and an array of parameters.

The value parameter (parameter) is used to pass the input parameter. A value parameter is equivalent to a local variable whose initial value is obtained from the argument passed for the parameter. Changes to a value parameter do not affect the arguments that are passed.

Reference parameters (reference parameter) are used for the delivery of input and output parameters. The argument used to reference a parameter must be a variable and, during the execution of the method, the reference parameter and the variable that is the independent variable represent the same storage location. Reference parameters are declared with a 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"

}

}

The output parameter (outputs parameter) is used for delivery of output parameters. An output parameter is similar to a reference parameter, except that the initial value of the argument supplied by the caller does not matter. Output parameters are declared with an out modifier. The following example shows the use of out parameters:

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 (3, out res, out REM);

Console.WriteLine ("{0} {1}", res, REM); Output "3 1"

}

}

The parameter array (parameter array) allows a variable-length list of arguments to be passed to the method. The parameter array is declared with the params modifier. Only the last parameter of a method can be declared as a parameter array, and it must be a one-dimensional array type. The Write and WriteLine methods of the System.Console class are good examples of parameter array applications. They are declared in the following form:

public class Console

{

public static void Write (String fmt, params object[] args) {...}



public static void WriteLine (String fmt, params object[] args) {...}

...

}

When you use a parameter array in a method, the parameter array behaves just like a regular array type parameter. However, in a method call with an array parameter, you can either pass a single argument of the parameter array type, or you can pass several arguments of the element type of the parameter array. For the latter case, the array instance is automatically created and initialized with the 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 bodies and local variables
The method body specifies the statement to execute when the method is called.

A method body can declare a variable that is specific to that method call. Such a variable is called a local variable (variable). A local variable declaration specifies a type name, a variable name, and possibly an initial value. The following example declares a local variable I with an initial value of 0; another local variable J has no 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 a local variable to be definitely assigned (definitely) before its value is obtained. For example, assuming that the previous variable I declaration does not contain an initial value, then the use of I in the next will cause the compiler to report an error because I do not have a definite assignment in the program.

method to return control to its caller by using the returns statement. If the method is void, the return statement cannot specify an expression, and if the method is not void, the returns statement must contain an expression to evaluate the returned value.

1.6.5.3 static method and instance method
If a method declaration contains a static modifier, the method is said to be static (static method). Static methods do not operate on a specific instance and can only access static members.

If there is no static modifier in a method declaration, the method is called an instance method (instance). An instance method operates on a specific instance to access both static members and instance members. On an instance of invoking an instance method, you can use this to access the instance, and it is an error to refer to this in a static method.

The following entity class has both static and instance members:



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 assumes that some other information is omitted). The entity constructor (similar to an instance method) Initializes a new instance with the next valid sequence number. Because the constructor is an instance member, it can access either the Serialno instance field or the nextSerialNo static field.

GetNextSerialNo and SetNextSerialNo static methods can access nextSerialNo static fields, but an error occurs if the Serialno instance field is accessed.

The following example shows the use of the entity class:

Using 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 the SetNextSerialNo and GetNextSerialNo static methods are invoked through the class, while Getserialno instance members are invoked through instances of the class.

1.6.5.4 virtual methods, overriding methods, and abstract methods
If the declaration of an instance method contains a virtual modifier, the method is said to be a dummy method. If there is no virtual modifier, the method is said to be Non-virtual (Nonvirtual method).

In a virtual method invocation, the Run-time type of the instance involved in the call (runtime type) determines which implementation of the method is to be invoked. In Non-virtual method invocations, the compile-time type of the instance (Compile-time type) is the determining factor.

A virtual method can be overridden by a derived class (override) 7 implementation. When an instance method declaration contains a override modifier, the method overrides the virtual method of the same signature that is inherited. A virtual method declaration is used to introduce a new method, and an override method declaration is used to make an existing inherited virtual method specialized (by providing a new implementation of the method).

Abstract methods are virtual methods that are not implemented. The declaration of an abstract method is implemented through the abstract modifier, and only the abstract method declaration is allowed in an abstract class. Derived classes of Non-abstract classes need to override abstract methods.

The following example declares an abstract class expression, which represents the node of an expression tree, and it has three derived class constant,variablereference,operation that implement the expression tree node for constants, variable references, and arithmetic operations.

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 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 '/': return x/y;

}

throw new Exception ("Unknown operator");

}

}

The preceding 4 classes are used to model arithmetic expressions. For example, using an instance of these classes, an expression x+3 can be represented as follows:

Expression e = new Operation (

New VariableReference ("X"),

'+',

New Constant (3));

The Evaluate method of the expression instance is called to evaluate the value of the expression, resulting in a double value. The method obtains a Hashtable containing the variable name (the input key) and the value (the input value) as its argument. The Evaluate method is a virtual abstract method, meaning that a derived class must override it and provide an actual implementation.

The constant implementation of the Evaluate method simply returns the saved constants. The VariableReference implementation finds the variable name in hashtable and returns the corresponding value. The operation implementation first computes the value of the left operand and the right-hand operand (calling the Evaluate method recursively), and then performs the given arithmetic operation.

The following program uses the expression class to compute the expression x* (y+2) for different values of x and Y.

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 (E.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 multiple methods to be declared with the same name in the same class, provided that their signatures are unique. Overloading When compiling a call to an overloaded method, the compiler uses overload resolution (overload resolution) to determine which method should be invoked. Overload resolution finds the best way to match the argument, or reports an error message if the best match method is not found. The following example shows the overload resolution mechanism. The comments in each invocation in the main method illustrate the method that is actually invoked.

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 ("F (Double)");

}

static void F (double x, dpuble y) {

Console.WriteLine ("F (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 previous example, a specific method is always selected by means of an explicit type conversion from a variable to a parameter type.

1.6.6 other function members
A function member of a class is a member that contains an executable statement. The method described in the previous section is the primary function member. This section discusses several other C # supported function members: constructors, properties, indexers, events, operators, destructors.

Table 1.8 shows a class named list that implements a list of extensible objects. This class contains examples of several function members that are most commonly used.

Example of function members in table 1.8 class

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 < count) value = Count;

if (value!= items. Length) {

object[] NewItems = new Object[value];

Array.copy (items, 0, NewItems, 0, Count);

Items = NewItems;

}

}

}
Property



public Object This[int Index] {

get {

return Items[index];

}

set {

Items[index] = value;

Onlistchange ();

}

}
Indexing device

public void Add (item) {

if (count = = Capacity) Capacity = count * 2;

Items[count] = Item;

count++;

OnChanged ();

}

protected virtual void onchanged () {

if (Changed!= null) Changed (this, eventargs.empty);

}

public override bool Equals (object other) {

Return Equals (This,other as List);

}

static bool Equals (List a,list b) {

if (a = = null) return b = null;

if (b = = NULL | | a.count!= b.count) return false;

for (int i = 0; i < A.count; i++) {

if (!object. Equals (A.item[i], b.item[i]) {

return false;

}

}

}
Method

public event EventHandler Changed;
Event

public static BOOL operator = = (List A, List B) {

Return Equals (A, b);

}

public static bool operator!= (List A, List B) {

Return! Equals (A, b);

}
Operator

}


1.6.6.1 Constructors
C # supports both instance constructors and static constructors. An instance constructor (instance constructor) is a member that implements the actions required to initialize an instance of a class. A static constructor (constructor) is a member that is used to implement the action required to initialize the class itself when the class is first loaded.

A constructor's declaration is like a method, but it has no return type, and its name is the same as the class name that contains it. If the declaration of a constructor contains a static modifier, it declares a statically constructed function, or declares an instance constructor.

Instance constructors can be overloaded. For example, the list declares two instance constructors, one with no arguments and one with an int parameter. Use the new operator to invoke an instance parameter. The following statement creates two list instances using the constructors of each list class.

List list1 = new list ();

List list2 = new list (10);

An instance constructor is not inherited, unlike other methods. Also, a class cannot have other instance constructors other than its own declared instance constructors. If a class does not declare any instance constructors, it is automatically provided with a default null instance constructor.

1.6.6.2 Property
A property is a natural extension of a field, both of which are named members with associated types, and the syntax for accessing fields and properties is the same. However, unlike a field, a property does not represent a storage location. Instead, properties have accessors (accessor) that specify the statements to be executed when their values are read or written.

The declaration of a property is similar to a field, except that the declaration of the property ends with a get accessor and/or a set accessor between delimiters {}, not a semicolon. Properties that contain both a get accessor and a set accessor are called Read-write properties (Read-write property). Properties that have only a get accessor are called read-only properties (Read-only property). Properties that have set accessors only are called write-only properties (Write-only property).

A get accessor is equivalent to a parameterless method with the return value of an attribute type. In addition to being the target of an assignment, when a property is referenced in an expression, the get accessor of the property is called to compute the value of the property.

A set accessor is equivalent to an argument with a single name of value and a method with no return type. When a property is the target of an assignment, or is referenced as an operand of the + + or--operator, the set accessor is invoked, and the passed argument provides the new value.

The list class declares two property count and capacity, sequentially read-only and write-only. The following are examples of using these properties:

List names = new list ();

Names. Capacity = 100; Calling the set accessor

int i = names. Count; Call Get Accessor

Int j = names. Capacity; Call Get Accessor

Like fields and methods, C # supports both instance properties and static properties. A static property is one that has a static modifier in the declaration, and the instance property does not.

The accessor of a property can be virtual. When the property declaration contains the Virtual,abstract,override modifier, they are applied to the property accessor.

1.6.6.3 Indexing Device
An indexer is such a member that it enables an object to be indexed in the same way as an array. The declaration of an indexer is similar to a property, except that the name of the member is this, and the following argument list is between the delimiters ([]). The parameter is available in the accessor of the indexer. Like properties, indexers can be read-write, read-only, write-only, and the accessors of an indexer can also be virtual.

The list class declares a single read-write indexer that accepts an int parameter. It is possible to index the list instance with an int value through the indexer. For example:

List names = new list ();

Names. ADD ("Liz");

Names. ADD ("Martha");

Names. ADD ("Beth");

for (int i = 0; i < names. Count; i++) {

string s = (string) names[i];

Names[i] = S.toupper ();

}

Indexers can be overloaded, meaning that multiple indexers can be declared as long as they have a different number or type of arguments.

1.6.6.4 Events
An event is a member that enables an object or class to provide notification. The declaration of an event is similar to a field, except that the event declaration contains an event keyword, and the type of the event declaration must be a delegate type.

In the class that contains the event declaration, the event can be used like a field of a delegate type (such an event cannot be abstract, and an accessor cannot be declared). This field holds a reference to a delegate that indicates that the event handler has been added to the event. If no event handlers have been added, the field is null.

The list class declares a single event member named changed, and the changed event indicates that a new item was added to the list of event handlers, which is raised by the onchanged virtual method, which first checks whether the event is null (meaning there is no event handler). The notification that raises an event is exactly equivalent to the delegate represented by the invocation event--Therefore, no special language widget is required to raise the event.

The customer responds to the event through an event handler (handler). Use the "=" operator to add or remove an event handler using "-=". 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 (Changecount); Output "3"

}

}

For more advanced scenarios that require the underlying storage of the control event 8, the declaration of an event can explicitly provide add and remove accessors, which are somewhat similar to the set accessors of a property.

1.6.6.5 operator
An operator (operator) is a function member that defines the meaning of a particular expression operator that can be applied to a class instance. There are three kinds of operators that can be defined: unary, two, and conversion operators. All operators must be declared public and static.

The list class declares two operators, the operator "= =" and the operator "!=", and assigns new meanings to the expressions that apply these operators to the list instance. Specifically, these operators define equality comparisons for two list objects, that is, they are compared using their Equals method. 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 outputs True because the two-List collection object contains objects with the same number and values. If the list does not define operator "= =", then the first Console.WriteLine will output false because A and B refer to different list instances.

1.6.6.6 destructor
A destructor (destructor) is a member of the action required to implement an instance of the destructor class. Destructors cannot have parameters, cannot have accessibility modifiers, and cannot be invoked explicitly. Destructors for the involved instances are automatically invoked during garbage collection.

The garbage collector takes a loose policy in deciding when to reclaim objects and run destructors. In particular, it is noted that the timing of the invocation of a destructor is indeterminate, and the destructor may run on any thread. For these or other reasons, the class implements the destructor only if there are no other viable solutions.


Related Article

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.