C # language primary entry

xiaoxiao2021-03-06  42

The simplest C # program

First let's see the standard Hello World program. Create a new file helloWorld.cs with a text editor, put the following code in this file:

// First C # program

Class HelloWorld {static void main () {system.console.writeline ("Hello World!");}}

Now, go to the DOS command window to save the directory of the HelloWorld.cs, then execute:

CSC HelloWorld.cs

This command compiles the source code and generates a HelloWorld.exe file. You can see this execution file:

Hello World!

Let's analyze this example. The first line of code is a line of comments, starting with "//". Like C / C and Java, "//" tells the compiler to ignore the content of the line until the end. Another annotation method in C # is a block annotation. The block comment starts by "/ *" to "* /".

The second important place in the program is the declaration of the fourth line main () method (Static void mian () {). Each C # program contains a main method, which is the starting point and end point of the program execution. Also note that the main () method of the HelloWorld class is defined as a static method. The main method of the program will never be globally, which means that the main method must be included in the class, such as this example in this example () is in the class HelloWorld (the main method can also contain the structure, but generally it is always Inside the class).

The last critical place in the program is to output the code of the text to the console, ie "System.Console.writeline (" Hello World! ");". WriteLine is a method defined in the Console class. WriteLine () outputs text to standard output devices and wraps. The Console class is included in the System Namespace (Collection of Class). If you want to avoid using the "system.console" way to point out the full name of the Console class, you can add "Using System;" in the beginning of the file, you can write directly "Console.Writeline" later. ");"

The following example demonstrates how to create and use the user-defined class and how to create a dynamic link library. Create two files using the text editor. The first is apple.cs, the content is as follows: public class apple {

Private string variety = ""

Public apple (string applevariety) {this.variety = applevariety;

Public void outputvariety () {system.console.writeLine (variety);

}

The second file is eXample2.cs, the content is as follows:

Class example2 {

Static void main () {Apple Mac = New Apple ("Macintosh"); Apple Gra = New Apple ("Granny Smith"); Apple Cor = New Apple ("Cortland"); mac.outputVariety (); gra.outputvariety ( Cor.OutputVariety ();}}

First, we define a new user definition class, the name is Apple. Although the Apple class does not have to put it in a separate file, it is a good object-oriented program habit in the independent file, which helps to simplify organization and management. We add a public class apple for the Apple class, so that other classes can create an instance of the Apple class. The next line code defines the instance variable Variety. After using the modifier private, only the Variety variable can be accessed directly in the Apple class. This is a common object-oriented programming habit called package. After the encapsulation, the details of the object are hidden in the user's users. The keyboard you are now using is a good example in the real world. We don't fully understand how keywords are sent to the controller (most of us don't know), but just understand how its interface is working. For example, we know that open the text editor, press the "&" button on the keyboard, "&" "will appear on the screen. If each person must understand the work details of the keyboard instead of understanding its interface, there will be no many people use it.

The next three lines of code are:

Public apple (string applevariety) {this.variety = variety;

These three lines of code define the constructor of the Apple class. The constructor of the class is similar to a blueprint that describes how to create class instances. We can easily distinguish between other methods of constructors and classes, because constructor always has the same name. In this example, the constructor of the class app has a string parameter, which is then saved to the instance variable Variety.

The last method of the Apple class is OutputVariety (). This method provides an interface for accessing instance variables, so it is called Accessor Method.

Let's take a look at the Example2 class. This example is the different example of the foregoing example in being to create and use the user-defined instance of the class apple. We created an instance of three Apple classes with the New operator. When you create an instance of the class, we don't have to explicitly call the constructor, the New operator will automatically call our call to constructor. After creating three Apple classes, we call the outputvariety method of these three objects, and output the value of these three objects by OutputVariety method.

Let's compile and run this example. First we have to compile the Apple class into a dynamic link library, the command is as follows:

CSC / Target: library apple.cs

/ Target: library means not to create an execution file, but create a .dll file (ie dynamic link library). So, the above command will generate an apple.dll file.

Next we compile the example2.cs, the compile command is as follows:

CSC /Reference :apple.dll esample2.cs

Now we get executive files example2.exe. Executing this file can see the following output on the console: Macintoshgranny SmithCortland

In this last example, let's take a look at the abstraction and polymorphism of C #. First let's define these two new terms. Abstract is achieved by extracting a common part from multiple objects and incorporating them into separate abstract classes. In this case we will create an abstract class shape. Each shape has a method of returning its color. Whether it is a square or a circular shape, a rectangle, the return color method is always the same, so this method can be extracted into the parent class Shape. This way, if we have 10 different shapes that need to have a color method, now just create a method in the parent class. It can be seen that the use of abstraction makes the code more short. In object-oriented programming, polymorphism is the ability to make different behavior depending on the class. In the following example, abstract class shape has a getArea () method, which has different functions for different shapes (circles, squares or rectangles).

Below is the code:

Public Abstract Class Shape {Protected String Color; Public Shape (String Color) {this.color = color;} public string getColor () {Return Color;} public abstract double getarea ();

public class Circle: Shape {private double radius; public Circle (string color, double radius): base (color) {this.radius = radius;} public override double getArea () {return System.Math.PI * radius * radius; }

Public Class Square: Shape {Private DoubleLelen; PUBLIC SQUARE (String Color, Doublelen): Base (color) {this.sidelen = Sidelen;} public override double getarea () {return sidelen * sidelen;}}

/ * Public class Rectangle: Shape ... ... * /

Public class example {static void main () {shape mycircle = new circle ("Orange", 3); Shape MyRectangle = New Rectangle ("Red", 8, 4); Shape MySquare = New Square ("Green", 4) System.console.writeline ("Round color is" mycircle.getcolor () "It is" mycircle.getarea () "."); System.console.writeline ("Rectangular color is" myRectangle.getColor () "It is" " ". "); system.console.writeline (" Square color is " mysquare.getColor () " It is " mysquare.getarea () ".");}}

The first class we created is Shape. This is an abstract class because we don't want to create instances of this class, we want to create an instance of its derived class. We extract common features from all shapes (circles, rectangles, squares). The Shape class has an instance variable color, which has a protected modifier in its variable declaration. The protected modifier indicates that this variable can only be accessed within the interior of the class or in the derived class of the class. This variable is declared is the constructor and access method of the Shape class getColor (), which is nothing new. The last method getArea () adds Abstract modifiers because each different shape has different area calculation methods, so this method must be defined by various shapes. The next three class Circle, Rectangle, and Square are derived from the Shape class, which have the features described in Shape. This can be seen from their definitions, and their declarations have "public class: shape {", this ": shape" means the current class is derived from the Shape class. Since these three classes are derived from Shape, they automatically have all public or protected instance variables defined in Shape, which is Circle, Rectangle, and Square contain instance variables Color.

Every Sharp's derived class has its own constructor, which is responsible for calling the constructor of the parent class Shape Setting the public instance variable (color) and setting the instance variables that own yourself. For example, "public circle (string color, double radius): base (color)", ": Base (color)" means the constructor of the parent class with the parameter color.

Finally, let's take a look at the getArea () method, it is a polymorphic demonstration. All shapes have a getArea () method, but the method of the specific call is different depending on the object, the rectangle is also square.

To run this example, save all files to the same directory, then execute the following command:

CSC / Target: library /out:shapes.dll shapes.cs circle.cs rectangle.cs square.cs

Then execute:

CSC /Reference:SHAPES.DLL EXAMPLE3.CS

Now, if we run Example3.exe, we will get the following output:

The round color is Orange its area is 28.274333882308138. Square color is Green its area is 16. The rectangular color is RED its area of ​​32.

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

New Post(0)