Chapter 5 Category 1)

Source: Internet
Author: User

Chapter 5 Category 1)
The previous chapter discusses data types and their usage. Now we move to the key structure-class in C. Without classes, even simple C # programs cannot be compiled. This chapter assumes that you know the basic components of a class: Methods, attributes, constructors, 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 the constructor of the corresponding class. Even
If you do not write a constructor, a default constructor is 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, constructors are always public. You can use them
Initialize the variable.

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

If a class only contains static members (which can be called by type, rather than by instance), you can create a private constructor.
Private TestClass (){}
Although the access modifier will be discussed later in this chapter, private means that it is impossible to access the constructor from outside the class. Institute
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 there is no return value in the constructor. Of course, although
C # does not return values, but you can raise a self-made exception to obtain the returned values from the constructor. For more information about exception handling, see Chapter 7 "Exception
Processing is discussed.
However, when you retain the referenced resources, you should think of writing a method to solve the problem: one can be explicitly called to release these resources. The problem is
When you can add "~ "), Why do we need to write an additional method when doing the same thing.
Public ~ TestClass ()
{
// Clear
}

The reason you should write an additional method is the garbage collector, which will not be called immediately after the variable is out of the range, but only when the interval or memory condition is full
Trigger only when sufficient. When you lock a resource for a longer time than you planned, it will happen. Therefore, an explicit release method is a good master.
It 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 it is a good habit to forget to clear it.

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 of the function can be obtained in the method.
To implementation. You have already seen the use of static methods, but these are the parts of the type (class), not the 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 involve
The problem caused by retrieving the returned results.

. Input parameters
. Reference parameters
. Output Parameters

5.2.1.1 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 method through a value-the method variable is called
A copy of the value passed by the user is initialized. Listing 5.1 demonstrates the use of input parameters.

Listing 5.1 passing parameters through values

1: using System;
2:
3: public class SquareSample
4 :{
5: public int CalcSquare (int nSideLength)
6 :{
7: return nSideLength * nSideLength;
8 :}
9 :}
10:
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 (25) can be used when calling a method (see row 16th ). Integer result returned
Return value to the caller. If the caller does not store 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, note that no implicit ByVal or ByRef-can be processed by the compiler-
-If this parameter is not set, the parameter is always passed as a value.
This seems to conflict with what I mentioned earlier: for some variable types, passing values actually means passing with references. Confused? Background Knowledge
It is not required: The thing in COM is the interface. Each class can have one or more interfaces. An interface is just a set of function pointers and does not contain data.
Repeat the array will waste a lot of memory resources. Therefore, only the starting address is copied to the method. As the caller, it still points to the same pointer of the interface. That is
The object that uses the value to pass a reference.

5.2.1.2 reference parameters
Although many methods can be created using input parameters and return values, you don't have to think of passing a value and modifying it in the same place (that is, in the same memory location ).
Good luck. 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 use
A reference parameter creates a method.

Listing 5.2 passing parameters through reference

1: // class SquareSample
2: using System;
3:
4: public class SquareSample
5 :{
6: public void CalcSquare (ref int nOne4All)
7 :{
8: nOne4All * = nOne4All;
9 :}
10 :}
11:
12: class SquareApp
13 :{
14: public static void Main ()
15 :{
16: SquareSample sq = new SquareSample ();
17:
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 can use them to calculate the results.
And return the result. However, in real applications, I strongly recommend that you use two variables, one input parameter and one reference parameter.

5.2.1.3 output parameters
The third choice for passing parameters is to set it as an output parameter. As this name implies, an output parameter is only used to pass a result from a method.
Another difference between it and the referenced parameter is that the caller does not need to initialize the variable before calling the method. This is shown in listing 5.3.

Listing 5.3 defines an output parameter

1: using System;
2:
3: public class SquareSample
4 :{
5: public void CalcSquare (int nSideLength, out int nSquared)
6 :{
7: nSquared = nSideLength * nSideLength;
8 :}
9 :}
10:
11: class SquareApp
12 :{
13: public static void Main ()
14 :{
15: SquareSample sq = new SquareSample ();
16:
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 designed a method for rewriting
In the derived class, you can redefine (rewrite) the methods of the base class. The Basic programmer can use the 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: 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.