Chapter V. net Programming pioneer C #

Source: Internet
Author: User

Chapter 5
The previous chapter discusses data types and their usage. Now we move to the key structure-class in C. No
Class, even simple C # programs cannot be compiled. This chapter assumes that you know the basic components of a class: Methods, attributes, and structure.

Create functions and destructor. C # adds indexes and events.
In this chapter, you will learn the following topics about classes.
. Use constructor and destructor
. Class Writing Method
. Adds a property access flag to a class.
. Index implementation
. Create an event and associate the customer with the event by representing the element
. Application class, members, and access modifier.

5.1 constructor and destructor
Before you can access a class's methods, attributes, or anything else, the first statement to be executed contains

Constructor of the class. Even if you do not write a constructor yourself, a default constructor will be provided to you.

Class TestClass
Public TestClass (): base () {}// provided by the compiler

A constructor is always the same as its class name, but it does not declare the return type. In short, constructor always

Public, you can use them to initialize variables.

Public TestClass ()
// Give the variable
// Initialization code and so on.

If the class only contains static members (which can be called by type, rather than by instance), you can create

Private constructor.
Private TestClass (){}
Although the access modifier will be discussed in a large space later in this chapter, private means that it is impossible to get out of the class.

Access this constructor. Therefore, it cannot be called, and no object can be customized to be instantiated.
It is not limited to the non-parameter constructor. You can pass the initial parameter to initialize the member.
Public TestClass (string strName, int nAge ){...}

As a C/C ++ programmer, you may be used to writing an additional method for initialization, because the constructor does not

Return Value. Of course, although there is no return value in C #, you can raise a self-made exception to get the return value from the constructor.

Value. More information about exception handling is discussed in Chapter 7 "Exception Handling.
However, when you retain references to valuable resources, you should think of writing a method to solve the problem: one can be explicitly called

Release these resources. The problem is that you can add "~ When you do the same thing

He also needs to write an additional method.
Public ~ TestClass ()
// Clear

The reason you should write an additional method is the garbage collector, which is not called immediately after the variable is out of the range, but only when

Triggered only when the interval or memory conditions are met. When you lock a resource for a longer time than you planned, it will happen.

Therefore, it is a good idea to provide an explicit release method, which can also be called from the destructor.

Public void Release ()
// Release all valuable resources

Public ~ TestClass ()
Release ();

Calling the release method in the Destructor is not necessary-in short, garbage collection will pay attention to releasing objects. But did not forget to clear

Aside from being a good habit.

5.2 Method
Since the object can be correctly initialized and ended, all that is left is to add features to the class. In most cases

The main part can be implemented in the method. You have already seen the use of static methods, but these are the parts of the type (class), not

Instance (object ).
To help you get started quickly, I have arranged three cumbersome problems for these methods:
. Method Parameters
. Rewrite Method
. Method shielding
5.2.1 method parameters
Because the method must process and change the value, you must pass the value to the method more or less and obtain the return value from the method. The following three parts are involved:

The problem caused by passing the value and obtaining the returned result by the caller.

. Input parameters
. Reference parameters
. Output Parameters input parameters
One Parameter you have already seen in the example is the input parameter. You use an input parameter to pass a variable to a party through a value.

Method-the method variable is initialized by a copy of the value passed by the caller. Listing 5.1 demonstrates the use of input parameters.

Listing 5.1 passing parameters through values

1: using System;
3: public class SquareSample
4 :{
5: public int CalcSquare (int nSideLength)
6 :{
7: return nSideLength * nSideLength;
8 :}
9 :}
11: class SquareApp
12 :{
13: public static void Main ()
14 :{
15: SquareSample sq = new SquareSample ();
16: Console. WriteLine (sq. CalcSquare (25). ToString ());
17 :}
18 :}

Because I pass a value instead of referencing it to a variable, a constant expression can be used when calling a method (see row 16th ).

(25 ). The integer result is returned to the caller as the return value. If it is not stored in the intermediate variable, it is immediately displayed on the screen.
Input parameters work according to the way C/C ++ programmers are used. If you are from VB, please note that it cannot be processed by the compiler

Implicit ByVal or ByRef -- if not set, the parameter is always passed with a value.
This seems to conflict with what I mentioned earlier: for some variable types, passing values actually means passing with references.

Confused? You do not need any background knowledge: interfaces are the things in COM. Each class can have one or more interfaces. One

An interface is just a set of function pointers that do not contain data. Repeat the array will waste a lot of memory resources; therefore, only the start address

It is copied to the method. As the caller, it still points to the same pointer of the interface. That is why an object uses a value to pass a reference. reference parameters
Although many methods can be created using input parameters and return values, you can think of passing a value and modifying it in the same place (that is

The same memory location. Reference parameters are convenient here.
Void myMethod (ref int nInOut)
Because you pass a variable to this method (not just its value), the variable must be initialized. Otherwise, the compiler will trigger an alarm.

Listing 5.2 shows how to create a method with a reference parameter.

Listing 5.2 passing parameters through reference

1: // class SquareSample
2: using System;
4: public class SquareSample
5 :{
6: public void CalcSquare (ref int nOne4All)
7 :{
8: nOne4All * = nOne4All;
9 :}
10 :}
12: class SquareApp
13 :{
14: public static void Main ()
15 :{
16: SquareSample sq = new SquareSample ();
18: int nSquaredRef = 20; // be sure to initialize
19: sq. CalcSquare (ref nSquaredRef );
20: Console. WriteLine (nSquaredRef. ToString ());
21 :}
22 :}

As you can see, all you need to do is to add the ref qualifier to the given and called calls. Because variables are passed through references, you

You can use it to calculate the result and return the result. However, in real applications, I strongly recommend that you use two variables:

Input parameters and reference parameters. output parameters
The third choice for passing parameters is to set it as an output parameter. As this name implies, an output parameter is used only from

Method to pass back a result. Another difference between it and the referenced parameter is that the caller does not need to initialize the variable before calling the method. This

Shown in listing 5.3.

Listing 5.3 defines an output parameter

1: using System;
3: public class SquareSample
4 :{
5: public void CalcSquare (int nSideLength, out int nSquared)
6 :{
7: nSquared = nSideLength * nSideLength;
8 :}
9 :}
11: class SquareApp
12 :{
13: public static void Main ()
14 :{
15: SquareSample sq = new SquareSample ();
17: int nSquared; // Initialization is not required.
18: sq. CalcSquare (15, out nSquared );
19: Console. WriteLine (nSquared. ToString ());
20 :}
21 :}

5.2.2 rewrite Method
An important principle of object-oriented design is polymorphism. Ignore profound theories. polymorphism means that when a base-class programmer has

When you design a method for rewriting, You can redefine (rewrite) the method of the base class in the derived class. Basic programmers can use

Virtual keyword design method:
Virtual void CanBOverridden ()
When derived from the base class, all you need to do is add the override keyword in the new method:
Override void CanBOverridden ()
When you rewrite a base class method, you must understand that you cannot change the access attribute of the method.


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: 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.