C # example of writing a method

Source: Internet
Author: User

 

Develop application logic

1. Open the DailyRate project in the \ Microsoft Press \ Visual CSharp Step by Step \ Chapter 3 \ DailyRate subfolder under the My Documents folder in Visual Studio 2005.

2. In Solution Explorer, double-click the Program. cs file to display programs in the Code and text editor window.

3. Add the following statement to the main body of the run method:

Double dailyRate = readDouble ("Enter your daily rate :");
Int noOfDays = readInt ("Enter the number of days :");
Writerate (calculaterate (dailyRate, noOfDays ));

When the application starts, the run method is called by the Main method.

The code block added in the run method will call the readDouble method (this method will be written soon) so that users can enter the daily rate of the consultant. The next statement calls the readInt method (which will be written immediately) to obtain the number of days. Finally, the writeiterator method will be called (waiting for writing) to display the result on the screen. Note that the value passed to writeFee is the value returned by the calculateFee method (the last method to be written). This method obtains the daily rate and number of days and calculates the total amount to be paid.

Note: Because the readDouble, readInt, writeFee, or calculateFee methods have not been written, "smart sensing" cannot automatically list them when entering the above Code. In addition, do not try to generate a program first, because it will certainly fail.

Use the "generate method stub wizard" to compile the Method

1. In the "Code and Text Editor" window, click the readDouble method call in the run method.

A small underline icon is displayed below the first letter ("r") of readDouble. Move the mouse pointer to the letter "r" and an icon will automatically appear. Hover the mouse pointer over this icon, and a tooltip is displayed: "options used to generate method stubs (Shift + Alt + F10)", and a drop-down menu is provided. Click the drop-down menu and you will see an option: generate the "ReadDouble" method stub in "DailyRate. Program.

2. Click the "generate" ReadDouble "method stubs" option in "DailyRate. Program.

Then, the "generate method stub wizard" checks the call to the readDouble method, judges the parameter type and return value, and generates a method with default implementation, as shown below:

Private double readDouble (string p)
{
Throw new Exception ("The method or operation is not implemented .");
}

The new method is created using a private qualifier. Currently, the method subject only throws an exception. We will replace the subject with our own statement in the next step.

3. Remove throw new Exception (…) from the readDouble method (...); Statement to replace it with the following code lines:

Console. Write (p );
String line = Console. ReadLine ();
Return double. Parse (line );

The code block above outputs the string in Variable p to the screen. This variable is a string parameter passed by the call method, which contains a message prompting the user to enter the daily rate. You can enter a value that is read into a string using the ReadLine method and converted to a double value using the double. Parse method. The result is returned as the return value of the method call.

Note that the ReadLine method is used with WriteLine to read the user's input from the keyboard until you press the Enter key. The text entered by the user is returned as a return value.

4. In the run method, click the readInt method call to generate a method stub for the readInt method according to the same procedure as before.

The readInt method is generated using a default implementation.

Prompt: To generate a method stub, you can also right-click a method call and select "generate method stub" from the pop-up menu ".

5. Replace the subject of the readInt method with the following statement:

Console. Write (p );
String line = Console. ReadLine ();
Return int. Parse (line );

This code block is very similar to the readDouble method. The only difference is that the method returns an int value, so you must use the int. Parse method to convert the string to an integer.

6. Right-click the calculate method call in the run method and select "generate method stub ".

The calculateFee method will be generated later:

Private object calculaterate (double dailyRate, int noOfDays)
{
Throw new Exception ("The method or operation is not implemented ");
}

Note: The "generate method stub wizard" uses the passed real parameter name to generate the parameter name (you can change the name if it is inappropriate ). More interesting is the return type of the method, which is currently an object. This indicates that the "generate method stub wizard" cannot determine the type of value that the method should return based on the current context. The object type only means something. When adding specific code to a method, you should change it to the type you need.

7. modify the definition of the calculateFee method so that it returns a double value:

Private double calculaterate (double dailyRate, int noOfDays)
{
Throw new Exception ("The method or operation is not implemented ");
}

8. Replace the subject of the calculateFee method with the following statement. It calculates the product of the two parameter values to get the amount to be paid and returns the result.

Return dailyRate * noOfDays;

9. Right-click the writeiterator method call in the run method and select "generate method stub ".

The writeiterator method is generated later. Note: The "generate method stub wizard" determines based on the definition of the calculateFee method that the parameter of the writeFee method should be a double parameter. In addition, the method call does not use a return value, so the method type is void:

Private void writeFee (double p)
{
...
}

10. Enter the following statement in the writetasks method:

Console. WriteLine ("The consultant's succeeded is: {0}", p * 1.1 );

Note that the WriteLine method of this version demonstrates how to use a simple format string. {0} is a placeholder. When you evaluate a value, it is replaced by the value of the expression (p * 1.1) after the string.

11. Select "generate" | "generate SOLUTION ".
Code Reconstruction

One of the most useful features of Visual Studio 2005 is code refactoring. Sometimes, we need to write the same (or very similar) code in multiple locations of the application. In this case, you can select the entered code block, and then select "refactor" | "Extraction Method" from the menu bar ". The "Extract Method" dialog box appears, prompting you to enter the name of a new method that will contain the code you just entered. Enter a method name and click OK ". Then, the system will create this method and transfer the code you just entered to it. The code you just entered will be replaced with a call to this method. The "Extraction Method" also has some intelligence to determine whether the method should obtain any parameters and return values.

Test procedure

1. Select "debug" | "start execution (do not Debug)". Visual Studio 2005 generates a program and runs it. A console window is displayed during running.

2. After you Enter Your Daily Rate (Enter Daily Rate), Enter 525 and press Enter.

3. After Entering The Number Of Days prompt, Enter 17 and press Enter.

The program will display the following message on the console:

The consultant's timeout is: 9817.5

Press the Enter key to return to the Visual Studio 2005 programming environment.

In the last exercise, the Visual Studio 2005 debugger will be used to run the program at a slower pace. You will see the time when each method is called (this action is called jump) and how each return statement returns control to the caller (this action is called jump out ). When entering and leaving the method, you must use the tool on the "debug" toolbar. However, when running an application in debug mode, you can select the same command from the Debug menu.

Use the Visual Studio 2005 debugger to execute each method in sequence.

1. In the "Code and Text Editor" window, find the run method.

2. Align the mouse pointer with the first statement in the run method.

The first statement of the run method is:

Double dailyRate = readDouble ("Enter your daily rate :");

3. Right-click anywhere in the row and select "Run To cursor" from the pop-up menu ".

The program starts to run and is paused after the first statement of the run method is reached. A yellow arrow on the left side of the code and text editor window specifies the current statement, which is highlighted in a yellow background.

4. Select "View"> "toolbar" to confirm that the "debug" toolbar is selected. The "debug" Toolbar may be docked next to another toolbar. If you cannot find this toolbar, you can use the "toolbar" command in the "View" menu to temporarily hide it, and pay attention to which buttons have disappeared from the interface. Re-display the toolbar to know where it should appear.

Note: To separate the debugging toolbar, use the control point on the left of the toolbar and drag it to the top of the "Code and Text Editor" window.

5. Click the "Statement by statement" button on the "debug" toolbar. This action causes the debugger to jump into the method being called. The yellow arrow on the left points to the starting braces of the readDouble method. Click the "Statement by statement" button again, and the pointer will switch to the first statement: Console. Write (p );

The prompt press F11 is equivalent to clicking the "Statement by statement" button on the "debug" toolbar.

6. Click the "process-by-process" button on the "debug" toolbar. This causes the method to execute the next statement without debugging it. The yellow arrow points to the second statement of the method. The program displays the "Enter Your Daily Rate" prompt in a console window (the console window may be hidden behind Visual Studio 2005 ).

The prompt press F10 is equivalent to clicking the "process-by-process" button on the "debug" toolbar.

7. Click the "process-by-process" button on the "debug" toolbar. This time, the yellow arrow disappears and the Console window gets the focus, because the program is executing the Console. ReadLine method and requires the user to enter some content.

8. Enter 525 in the console and press enter to continue.

Then, the control will return Visual Studio 2005. The yellow arrow appears in the third line of the method.

9. Do not make any click action. Move the mouse pointer to the reference to the line variable in the second or third line of the method (it does not matter which line is targeted ).

A screen prompt is displayed, showing the current value of the line variable (525 ). With this feature, you can determine that the variable has been set as the expected value during method-by-method execution.

10. Click the "Jump Out" button on the "debug" toolbar.

This will cause the current method to continue running without interruption until the end. After the readDouble method is executed, the yellow arrow indicates the first statement of the run method.

The prompt "Shift + F11" is equivalent to clicking the "Jump Out" button on the "debug" toolbar.

11. Click the "Statement by statement" button on the "debug" toolbar.

The yellow arrow moves to the second statement of the run method:

Int noOfDays = readInt ("Enter the number of days :");

12. Click the "process-by-process" button on the "debug" toolbar.

This time, select the direct running method, and debug the method without statement. The console window appears again, prompting you to enter a number of days.

13. Enter 17 in the console window and press enter to continue.

Control is returned to Visual Studio 2005. The yellow arrow moves to the third statement of the run method:

Writerate (calculaterate (dailyRate, noOfDays ));

14. Click the "Statement by statement" button on the "debug" toolbar.

The yellow arrow jumps to the starting braces of the calculateFee method. This method will be called before the writeworkflow method.

15. Click the "Jump Out" button on the "debug" toolbar.

The yellow arrow jumps back to the third statement of the run method.

16. Click the "Statement by statement" button on the "debug" toolbar.

This time, the yellow arrow jumps to the starting braces of the writeworkflow method.

17. Align the mouse pointer with the p variable in the method definition.

The p value (8925.0) is displayed ).

18. Click the "Jump Out" button on the "debug" toolbar.

The message "The consultant's timeout is: 9817.5" will be displayed in The console window. (If The console window is hidden after Visual Studio 2005, bring it to The foreground for display ). The yellow arrow returns the third statement of the run method.

19. Click the "continue" button on the "debug" toolbar to run the program continuously without pausing each statement.

The application will run until it is finished.

The prompt is that you can press F5 to continue execution in the debugger.

Congratulations! You have successfully compiled and called methods and debugged them using the Visual Studio 2005 debugger.

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.