". NET programming Pioneer C #" Chapter Fifth Class (Turn)

Source: Internet
Author: User
Tags definition class definition constructor contains exception handling garbage collection variables tostring
Programming Chapter Fifth Class
The previous chapter discusses data types and their usage. Now we move to the most important structure in C #-class. Without
class, even simple C # programs cannot be compiled. This chapter assumes that you know the basic components of a class: methods, attributes, structure

Creating functions and destructors. C # has added indexes and events to it.
In this chapter, you learn the following topics about class.
。 Using constructors and destructors
。 Write method to Class
。 Add attribute access flags to a class
。 Implementing an Index
。 Create an event and associate a customer with an event by representing a dollar
。 Apply classes, members, and access modifiers.

5.1 Constructors and destructors
Before you can access a class's methods, properties, or anything else, the first executed statement contains a phase

The constructor of the expected class. Even if you do not write a constructor yourself, there will also be a default constructor provided to you.

Class TestClass
{
Public TestClass (): Base () {}//supplied by compiler
}

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

Public, you can use them to initialize variables.

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

If a class contains only static members (which can be invoked as a type instead of a member called by an instance), you can create a

The private constructor.
Private TestClass () {}
Although the access modifier will be discussed in greater detail later in this chapter, private means that it is impossible from outside the class

Access the constructor. Therefore, it cannot be invoked, and no object can be instantiated from that class definition.
is not limited to a parameterless constructor-you can pass the initial argument to initialize the member.
Public TestClass (string strName, int nage) {...}

You may be accustomed to writing an additional method for initialization as a C/C + + programmer, because there is no

The return value. Of course, although there is no return value in C #, you can throw a homemade exception to get the return from the constructor

Value. More knowledge of exception handling is discussed in the seventh chapter, "Exception Handling".
However, when you keep references to valuable resources, you should think of writing a method to solve: one can be explicitly called to

Release these resources. The problem is that when you do the same thing in the destructor (named in front of the class name plus "~"), the

How to write an additional method.
Public ~testclass ()
{
Clear
}

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

triggered during intermittent periods or when memory conditions are met. It happens when you lock the resource longer than you plan to time.

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

public void Release ()
{
Release all the valuable resources
}

Public ~testclass ()
{
Release ();
}

It is not necessary to call a release method in a destructor--in short, garbage collection will pay attention to releasing the object. But did not forget to clear

In addition to being a good habit.

5.2 Method
Now that the object can initialize and end correctly, what remains is adding functionality to the class. In most cases, the functionality of the

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

Instance (object).
In order to get you started quickly, I've arranged the tedious issues of these methods for the following sections:
。 Method parameters
。 Rewriting methods
。 Method Mask
5.2.1 Method Parameters
Because the method is going to handle changing values, you have to pass the value to the method more or less and get the return value from the method. The following three sections deal with

To the problem caused by passing the value and getting the returned result for the caller.

。 Input parameters
。 Reference parameters
。 Output parameters

5.2.1.1 Input Parameters
One of the parameters that you have seen in the example is the input parameter. You use an input parameter to pass a variable by value to a square

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

Listing 5.1 passing parameters by value

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 a reference to a variable, you can use a constant expression when calling a method (see line 16th)

(25). The integer result is passed back to the caller as the return value, and it is immediately displayed to the screen without saving to the intermediate variable.
Input parameters are working in a way that is already used by C + + programmers. If you are from VB, please note that no one can be handled by the compiler

An implicit ByVal or byref--parameter is always passed by value if it is not set.
This seems to conflict with what I have stated earlier: For some variable types, passing by value actually means passing by reference.

Are you confused? A bit of background knowledge does not need: COM is the thing is the interface, each class can have one or more interfaces. One

An interface is simply a set of function pointers that do not contain data. Repeating the array will waste a lot of memory resources; So, only start addresses

is copied to the method, which acts as the caller and still points to the same pointer to the interface. That's why the object passes a reference with a value.

5.2.1.2 Reference Parameters
Although you can use input parameters and return values to create many methods, you think of passing a value and modifying it in situ (i.e.

Same memory location), it's not that good luck. It is convenient to use reference parameters here.
void MyMethod (ref int ninout)
Because you pass a variable to the method (not just its value), the variable must be initialized. Otherwise, the compiler will alert you.

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

Listing 5.2 Passing arguments by 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 have to do is add a ref qualifier to both the definition and the call. Because variables are passed by reference, you

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

An input parameter and a reference parameter.

5.2.1.3 Output parameters
The third option for passing a parameter is to set it as an output parameter. As the name implies, an output parameter is used only from the

method to pass back a result. Another difference between it and reference parameters is that the caller does not have to initialize the variable before calling the method. This

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; Do not have to initialize
18:sq. Calcsquare (out nsquared);
19:console.writeline (Nsquared.tostring ());
20:}
21:}


5.2.2 Rewriting method
The important principle of object-oriented design is polymorphism. Ignore the advanced theory, polymorphism means: When the base class programmer has

When you design a method for rewriting, in a derived class, you can redefine (overwrite) the methods of the base class. The base class programmer can use

Virtual keyword Design method:
virtual void Canboverridden ()
When deriving from a base class, all you have to do is add the override keyword to the new method:
override void Canboverridden ()
When rewriting a method of a base class, you must understand that you cannot change the access property of the method--in the back of this chapter, you will learn

To more information about access modifiers.
In addition to overwriting the fact of the base class method, there is another, even more important, rewriting feature. When you cast a derived class to a base class

Type and then call the virtual method, the method that is invoked is the methods of the derived class rather than the base class.
((BaseClass) derivedclassinstance). Canboverridden ();
To demonstrate the concept of a virtual method, listing 5.4 shows how to create a triangular base class that has a system that can be changed

The member method written (Computearea).

Listing 5.4 Ways to rewrite a base class

1:using System;
2:
3:class Triangle
4: {
5:public virtual double Computearea (int a, int b, int c)
6: {
7://Heronian formula
8:double s = (A + B + C)/2.0;
9:double Darea = math.sqrt (s* (s-a) * (s-b) * (s-c));
10:return Darea;
11:}
12:}
13:
14:class Rightangledtriangle:triangle
15: {
16:public override double Computearea (int a, int b, int c)
17: {
18:double Darea = a*b/2.0;
19:return Darea;
20:}
21:}
22:
23:class Triangletestapp
24: {
25:public static void Main ()
26: {
27:triangle tri = new triangle ();
28:console.writeline (Tri.computearea (2, 5, 6));
29:
30:rightangledtriangle rat = new Rightangledtriangle ();
31:console.writeline (Rat.computearea (3, 4, 5));
32:}
33:}

The base class triangle defines the method Computearea. It takes three parameters, returns a double result, and has a public visit

Asking sex. Derived from the Triangle class is rightangledtriangle, which rewrites the Computearea method and implements its own

Calculation formula of the area. All two classes are instantiated and are obtained in the main () method of the application class named Triangletestapp

Verify.
I missed the explanation. Line 14th:
Class Rightangledtriangle:triangle
A colon (:) In a class statement indicates that Rightangledtriangle derives from the class triangle. That's all you have to do.

To let C # know that you want to treat triangle as a rightangledtriangle base class.
When you look closely at the Computearea method of the right-angled triangle, you will find that the 3rd parameter is not used for calculation. But, Lee

You can use this parameter to verify that it is "right angle." As shown in Listing 5.5.

Listing 5.5 calls the base class implementation

1:class Rightangledtriangle:triangle
2: {
3:public override double Computearea (int a, int b, int c)
4: {
5:const double Depsilon = 0.0001;
6:double Darea = 0;
7:if (Math.Abs (a*a + b*b-c*c)) > Depsilon)
8: {
9:darea = Base.computearea (a,b,c);
10:}
11:else
12: {
13:darea = a*b/2.0;
14:}
15:
16:return Darea;
17:}
18:}

This test simply uses the Pythagorean formula, and for a right-angled triangle, the test result must be 0. If the result is not 0, the class

It is implemented by invoking the computearea of its base class.
Darea = Base.computearea (a,b,c);
The point of the example is that you can easily invoke the base class implementation rewrite method by explicitly using the qualification check of the base class.
This is helpful when you need to implement its functionality in the base class rather than repeating it in a way that overwrites it.

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.