Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
26
Добавлен:
25.03.2016
Размер:
13.96 Mб
Скачать

Chapter 3 Writing Methods and Applying Scope

53

7.In the Code and Text Editor window, locate the showResult method. The showResult method looks like this:

private void showResult(int answer)

{

result.Text = answer.ToString();

}

This method contains one statement that displays a string representation of the answer parameter in the result text box.

Tip There is no minimum length for a method. If a method helps to avoid repetition and makes your program easier to understand, the method is useful regardless of how small it is.

There is also no maximum length for a method, but usually you want to keep your method code small enough to get the job done. If your method is more than one screen in length, consider breaking it into smaller methods for readability.

Calling Methods

Methods exist to be called! You call a method by name to ask it to perform its task. If the method requires information (as specified by its parameters), you must supply the information requested. If the method returns information (as specified by its return type), you should arrange to capture this information somehow.

Specifying the Method Call Syntax

The syntax of a C# method call is as follows:

result = methodName ( argumentList )

The methodName must exactly match the name of the method you’re calling. Remember, C# is a case-sensitive language.

The result = clause is optional. If specified, the variable identified by result contains the

value returned by the method. If the method is void (it does not return a value), you must omit the result = clause of the statement.

The argumentList supplies the optional information that the method accepts. You must supply an argument for each parameter, and the value of each argument must be compatible with the type of its corresponding parameter. If the method you’re calling has two or more parameters, you must separate the arguments with commas.

54

Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008

Important You must include the parentheses in every method call, even when calling a method that has no arguments.

To clarify these points, take a look at the addValues method again:

int addValues(int leftHandSide, int rightHandSide)

{

// ...

}

The addValues method has two int parameters, so you must call it with two commaseparated int arguments:

addValues(39, 3);

// okay

You can also replace the literal values 39 and 3 with the names of int variables. The values in those variables are then passed to the method as its arguments, like this:

int arg1 = 99; int arg2 = 1;

addValues(arg1, arg2);

If you try to call addValues in some other way, you will probably not succeed for the reasons described in the following examples:

addValues;

// compile-time error, no parentheses

addValues();

// compile-time error, not enough arguments

addValues(39);

//

compile-time error,

not enough arguments

addValues(“39”, “3”); //

compile-time error,

wrong types

The addValues method returns an int value. This int value can be used wherever an int value can be used. Consider these examples:

int result = addValues(39, 3); // on right-hand side of an assignment showResult(addValues(39, 3)); // as argument to another method call

The following exercise continues looking at the Methods application. This time you will examine some method calls.

Examine method calls

1.Return to the Methods project. (This project is already open in Visual Studio 2008 if you’re continuing from the previous exercise. If you are not, open it from the \Microsoft Press\Visual CSharp Step by Step\Chapter 3\Methods folder in your Documents folder.)

2.Display the code for Window1.xaml.cs in the Code and Text Editor window.

Chapter 3 Writing Methods and Applying Scope

55

3.Locate the calculateClick method, and look at the first two statements of this method after the try statement and opening brace. (We cover the purpose of try statements in Chapter 6, “Managing Errors and Exceptions.”)

The statements are as follows:

int leftHandSide = System.Int32.Parse(lhsOperand.Text); int rightHandSide = System.Int32.Parse(rhsOperand.Text);

These two statements declare two int variables called leftHandSide and rightHandSide.

However, the interesting parts are the way in which the variables are initialized. In both cases, the Parse method of the System.Int32 class is called (System is a namespace, and Int32 is the name of the class in this namespace). You have seen this method before; it takes a single string parameter and converts it to an int value. These two lines of code take whatever the user has typed into the lhsOperand and rhsOperand text box controls

on the form and converts them to int values.

4.Look at the fourth statement in the calculateClick method (after the if statement and another opening brace):

calculatedValue = addValues(leftHandSide, rightHandSide);

This statement calls the addValues method, passing the values of the leftHandSide and rightHandSide variables as its arguments. The value returned by the addValues method is stored in the calculatedValue variable.

5. Look at the next statement:

showResult(calculatedValue);

This statement calls the showResult method, passing the value in the calculatedValue variable as its argument. The showResult method does not return a value.

6.In the Code and Text Editor window, find the showResult method you looked at earlier. The only statement of this method is this:

result.Text = answer.ToString();

Notice that the ToString method call uses parentheses even though there are no arguments.

Tip You can call methods belonging to other objects by prefixing the method with the name of the object. In the preceding example, the expression answer.ToString() calls the method named ToString belonging to the object called answer.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]