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

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

16.Click Compare.

The following text appears in the text box:

first == second : False first != second : True first < second : True first <= second : True first > second : False first >= second : False

Again, these are the correct results when the first date is earlier than the second date.

17.Test some other dates, and verify that the results are as you would expect. Click Quit when you have finished.

Comparing Dates in Real-World Applications

Now that you have seen how to use a rather long and complicated series of if and else statements, I should mention that this is not the technique you would use to com-

pare dates in a real-world application. In the Microsoft .NET Framework class library, dates are held using a special type called DateTime. If you look at the dateCompare

method you have written in the preceding exercise, you will see that the two parameters, leftHandSide and rightHandSide, are DateTime values. The logic you have written

compares only the date part of these variables—there is also a time element. For two DateTime values to be considered equal, they should not only have the same date but

also the same time. Comparing dates and times is such a common operation that the DateTime type has a built-in method called Compare for doing just that. The Compare method takes two DateTime arguments and compares them, returning a value indicat-

ing whether the first argument is less than the second, in which case the result will be negative; whether the first argument is greater than the second, in which case the result will be positive; or whether both arguments represent the same date and time, in which case the result will be 0.

Using switch Statements

Sometimes when you write a cascading if statement, all the if statements look similar because they all evaluate an identical expression. The only difference is that each if compares the result of the expression with a different value. For example, consider the following block of

Chapter 4 Using Decision Statements

79

code that uses an if statement to examine the value in the day variable and work out which day of the week it is:

if (day == 0)

dayName = “Sunday”; else if (day == 1)

dayName = “Monday”; else if (day == 2)

dayName = “Tuesday”; else if (day == 3)

...

else

dayName = “Unknown”;

In these situations, often you can rewrite the cascading if statement as a switch statement to make your program more efficient and more readable.

Understanding switch Statement Syntax

The syntax of a switch statement is as follows (switch, case, and default are keywords):

switch ( controllingExpression )

{

case constantExpression : statements

break;

case constantExpression : statements

break;

...

default : statements break;

}

The controllingExpression is evaluated once. Control then jumps to the block of code identified by the constantExpression whose value is equal to the result of the controllingExpression. (The identifier is called a case label.) Execution runs as far as the break statement, at which point the switch statement finishes and the program continues at the first statement after the closing brace of the switch statement. If none of the constantExpression values are equal to the value of the controllingExpression, the statements below the optional default label run.

Note Each constantExpression value must be unique, so the controllingExpression will match only one of them. If the value of the controllingExpression does not match any constantExpression value, and there is no default label, program execution continues with the first statement after the closing brace of the switch statement.

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

For example, you can rewrite the previous cascading if statement as the following switch statement:

switch (day)

{

case 0 :

dayName = “Sunday”; break;

case 1 :

dayName = “Monday”; break;

case 2 :

dayName = “Tuesday”; break;

...

default :

dayName = “Unknown”; break;

}

Following the switch Statement Rules

The switch statement is very useful, but unfortunately, you can’t always use it when you may like to. Any switch statement you write must adhere to the following rules:

You can use switch only on primitive data types, such as int or string. With any other types (including float and double), you’ll have to use an if statement.

The case labels must be constant expressions, such as 42 or “42”. If you need to calculate your case label values at run time, you must use an if statement.

The case labels must be unique expressions. In other words, two case labels cannot have the same value.

You can specify that you want to run the same statements for more than one value by providing a list of case labels and no intervening statements, in which case the code for the final label in the list is executed for all cases in that list. However, if a label has one or more associated statements, execution cannot fall through to subsequent labels, and the compiler generates an error. For example:

switch (trumps)

 

{

 

case Hearts :

// Fall-through allowed – no code between labels

case Diamonds :

color = "Red";

// Code executed for Hearts and Diamonds

break;

 

case Clubs :

 

color = "Black";

// Error – code between labels

case Spades :

color = "Black";

 

break;

 

}

 

Chapter 4 Using Decision Statements

81

Note The break statement is the most common way to stop fall-through, but you can also use a return statement or a throw statement. The throw statement is described in Chapter 6,

“Managing Errors and Exceptions.”

switch Fall-Through Rules

Because you cannot accidentally fall through from one case label to the next if there is any intervening code, you can freely rearrange the sections of a switch statement without affecting its meaning (including the default label, which by convention is usually

placed as the last label but does not have to be).

C and C++ programmers should note that the break statement is mandatory for every case in a switch statement (even the default case). This requirement is a good thing; it is

very common in C or C++ programs to forget the break statement, allowing execution to fall through to the next label and leading to bugs that are very difficult to spot.

If you really want to, you can mimic C/C++ fall-through in C# by using a goto statement to go to the following case or default label. Using goto in general is not recommended,

though, and this book does not show you how to do it!

In the following exercise, you will complete a program that reads the characters of a string and maps each character to its XML representation. For example, the left angle bracket character, <, has a special meaning in XML (it’s used to form elements). If you have data that contains this character, it must be translated into the text “<” so that an XML processor knows that it is data and not part of an XML instruction. Similar rules apply to the right angle

bracket (>), ampersand (&), single quotation mark (‘), and double quotation mark (“) characters. You will write a switch statement that tests the value of the character and traps the

special XML characters as case labels.

Write switch statements

1.Start Visual Studio 2008 if it is not already running.

2.Open the SwitchStatement project, located in the \Microsoft Press\Visual CSharp Step by Step\Chapter 4\SwitchStatement folder in your Documents folder.

3.On the Debug menu, click Start Without Debugging.

Visual Studio 2008 builds and runs the application. The application displays a form containing two text boxes separated by a Copy button.

82

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

4. Type the following sample text into the upper text box:

inRange = (lo <= number) && (hi >= number);

5.Click Copy.

The statement is copied verbatim into the lower text box, and no translation of the <, &, or > character occurs.

6.Close the form, and return to Visual Studio 2008.

7.Display the code for Window1.xaml.cs in the Code and Text Editor window, and locate the copyOne method.

The copyOne method copies the character specified as its input parameter to the end of the text displayed in the lower text box. At the moment, copyOne contains a switch statement with a single default section. In the following few steps, you will modify this switch statement to convert characters that are significant in XML to their XML mapping. For example, the < character will be converted to the string “<”.

8.Add the following statements to the switch statement after the opening brace for the statement and directly before the default label:

case ‘<’ :

target.Text += “<”; break;

If the current character being copied is a >, this code will append the string “<” to the text being output in its place.

9.Add the following statements to the switch statement after the break statement you have just added and above the default label:

case ‘>’ :

target.Text += “>”; break;

case ‘&’ :

target.Text += “&”; break;

Chapter 4 Using Decision Statements

83

case ‘\”’ :

target.Text += “"”; break;

case ‘\’’ :

target.Text += “'”; break;

Note The single quotation mark (‘) and double quotation mark (“) have a special meaning

in C# as well as in XML—they are used to delimit character and string constants. The backslash (\) in the final two case labels is an escape character that causes the C# compiler to

treat these characters as literals rather than as delimiters.

10.On the Debug menu, click Start Without Debugging.

11.Type the following text into the upper text box:

inRange = (lo <= number) && (hi >= number);

12.Click Copy.

The statement is copied into the lower text box. This time, each character undergoes the XML mapping implemented in the switch statement. The target text box displays the following text:

inRange = (lo <= number) && (hi >= number)

13.Experiment with other strings, and verify that all special characters (<, >, &, “, and ‘) are handled correctly.

14.Close the form.

If you want to continue to the next chapter

Keep Visual Studio 2008 open, and turn to Chapter 5. If you want to exit Visual Studio 2008 now

On the File menu, click Exit. If you see a Save dialog box, click Yes (if you are using Visual Studio 2008) or Save (if you are using Visual C# 2008 Express Edition) and save the project.

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