<< Exhibition C # >> Chapter 6 Control Statement (Revised)

zhaozj2021-02-08  443

Chapter 6 control statement

There is a statement that you can find in each programming language control process statement. In this chapter, I introduce the C # control statement, which is divided into two main parts:

. Select statement

. loop statement

If you are C or C programmers, many information will make you feel similarity; however, you must know that there are still differences.

6.1 Selecting a statement

When using the selected statement, you define a control statement, which is controlled which statement is executed. Use two selection statements in C #:

. IF statement

. SWITCH statement

6.1.1 IF statement

The first and most commonly used statement is an IF statement. Whether or not the statement is executed depends on the Boolean expression:

IF (Boolean expression)

Of course, there is also an ELSE branch. When the value of the Boolean expression is false, the branch is performed:

IF (Boolean expression) contains statements ELSE

Check an example of a non-zero string before performing some statements:

IF (0! = strTest.Length)

{

}

This is a Boolean expression. (! = Said it is not equal.) However, if you use C or C , you may be used to writing code like this:

IF (strTest.length)

{

}

Such a write is no longer valid in C #, because if the IF statement accepts only the result of the Boo (Bool) type, the LENGTH property object of the string returns an integer. The compiler will appear the following error message:

Error CS0029: Cannot Implicitly Convert Type 'Int' To 'Bool' (cannot implicantly convert type 'int "is' bool'.)

You must change bad writing habits, don't appear in the IF statement, the following assignment error:

IF (nmyvalue = 5) ...

The correct code should be

IF (nmyvalue == 5) ...

Because it is equal to ==, it is like a C and C . Look at the following useful comparison operators (but not all data types are valid):

== - If the two values ​​are the same, return true.

! = - If the two values ​​are different, return false.

<, <=,>,> = - If the relationship is satisfied (less than, less than or equal to, greater than, greater than or equal to), return true.

Each operator is performed by the overload operator, and this execution is specified for the data type. If you compare two different types, for the compiler, there must be an implicit conversion to automatically create the necessary code. However, you can perform an explicit type conversion.

The code in Listing 6.1 demonstrates some different cases of the IF statement, and also demonstrates how to use string data types. The main idea of ​​this program is to determine whether the first parameter passed to the application starts with uppercase letters, lowercase letters or numbers.

Listing 6.1 Determines the form of characters

1: USING System;

2:

3: Class NestediFApp

4: {

5: public static int main (String [] ARGS)

6: {

7: IF (args.length! = 1)

8: {

9: console.writeline ("USAGE: One Argument"); 10: Return 1; // Error Level

11:}

12:

13: Char chletter = args [0] [0];

14:

15: IF (chletter> = 'a')

16: if (chletter <= 'z')

17: {

18: console.writeLine ("{0} is uppercase", chletter;

19: Return 0;

20:}

twenty one:

22: chletter = char.fromstring (args [0]);

23: IF (chletter> = 'a' && chletter <= 'z')

24: Console.WriteLine ("{0} is lowercase", chletter);

25:

26: IF (char.isdigit (chlletter = args [0])))))))))

27: console.writeLine ("{0} is a digit", chletter;

28:

29: RETURN 0;

30:}

31:}

Starting the first IF block detection parameter array has only one string parameter. If the condition is not met, the program displays usage information on the screen and terminates.

A variety of methods can extract a single character from a string - or use the character subscript as in line 13, or the static fromString method of the CHAR class, which returns the first character of the string.

The IF statements of the 16th to 20th line use a nested IF state block to check the uppercase letters. With logic "and" operators (&&) can be qualified for lowercase letters, and finally, by using a static function isDigit using a CHAR class, you can complete the detection of numbers.

In addition to "&&" operators, there is another conditional logic operator, which is representative "or" "||". Two logical operators are "short circuit". For the "&&" operator, it means that if the condition "and" the first result of the expression returns a false value, the remaining conditions "and" expressions will not be evaluated. Comparison, "||" operator When the first true condition is satisfied, it "short circuit".

I want everyone to understand that to reduce the calculation time, you should put the expression that is most likely to "short circuit" in front. Also you should be clear, calculate some of the values ​​in the IF statement in the danger.

IF (1 == 1 || (5 == (Strlength = str.length)))))))

{

Console.writeLine (Strlength);

}

Of course, this is an extremely exaggerated example, but it explains the view: the first statement evaluation is true, then the second statement will not be executed, it makes the variable strLength to maintain the original value. Give everyone an advice: Do not assign a value in the IF statement with conditional logic operators.

6.1.2 Switch statement

Compared to the IF statement, the Switch statement has a control expression, and the contents of the statement are running in accordance with the constant of the control expressions they associated.

Switch (Control Expression)

{

Case constant expression:

Internal statement

DEFAULT:

Internal statement

}

Controlling the data allowed by: Sbyte, Byte, Short, USHORT, UINT, LONG, ULONG, CHAR, STRING, or enumeration type. As long as other different data types can be implicitly converted to any type described, it is also very good to use it as a control expression. Switch statement is performed in the following order:

1, control expression evaluation

2. If the constant expression after the CASE tag meets the value obtained by the control statement, the contents are executed.

3. If there is no constant expression conforms to the control statement, the inherent statement in the Default tag is executed.

4. If there is no Case tag, and there is no DEFAULT tag, control the end of the end of the Switch segment.

Please check out the Switch statement in more detail, see Listing 6.2, which demonstrates the number of days in a month (ignore the year) with the Switch statement (ignore the year)

Listing 6.2 Use the switch statement to display a month of days

1: USING System;

2:

3: Class Fallthrough

4: {

5: public static void main (string [] args)

6: {

7: IF (args.length! = 1) return;

8:

9: int nmonth = int32.parse (args [0]);

10: IF (nmonth <1 || nmonth> 12) Return;

11: int NDAYS = 0;

12:

13: Switch (NMONTH)

14: {

15: Case 2: nDAYS = 28; Break;

16: Case 4:

17: Case 6:

18: Case 9:

19: Case 11: nDAYS = 30; Break;

20: DEFAULT: nDAYS = 31;

twenty one: }

22: console.writeline ("{0} days in this month", nDays);

twenty three: }

twenty four: }

Switch sections range from Sections 13 to 21. For C programmers, this looks very similar because it does not use the BREAK statement. Therefore, there is a more vital importance. You have to add a BREAK statement (or a different jump statement) because the compiler will remind, not allowing "Fall-Through" next part.

What is "straight"? In c (and C ), ignore Break and write code as follows:

NVAR = 1

Switch (nvar)

{

Case 1:

DOSMETHING ();

Case 2:

Domore ();

}

In this example, after executing the code of the first case statement, the code directly to other CASE tags is executed until a BREAK statement exits the Switch segment. Although it is sometimes a powerful function, it is often difficult to discover defects.

But if you want to execute the code of other CASE tags, how

Do you do it? There is an approach that it is displayed in Listing 6.3.

Listing 6.3 Using Goto Tags and Goto Default in SWTICH statements

1: USING System;

2:

3: Class Switchapp

4: {

5: public static void main ()

6: {

7: random objrandom = new random ();

8: Double DrndNumber = Objrandom.nextdouble (); 9: int NRNDNUMBER = (int));

10:

11: Switch (nrndnumber)

12: {

13: Case 1:

14: // Nothing

15: Break;

16: Case 2:

17: Goto Case 3;

18: Case 3:

19: Console.WriteLine ("Handler for 2 and 3");

20: Break;

21: Case 4:

22: Goto Default;

23: // Everything beyond a goto will be Warned AS

24: // Unreachable Code

25: DEFAULT:

26: console.writeLine ("Random Number {0}", NRNDNUMBER);

27:}

28:}

29:}

In this example, the value generated by the Random class will be used to control the expression (lines 7 ~ 9). The SWITCH block contains two trip statements that are valid for the Switch statement.

Goto Case Tags: Jump to the illustrated label

Goto Default: Jump to Default Tag

With these two jump statements, you can create functions as C, but straight through no longer automatic. You must ask it clearly.

A deeper meaning of the direct function is no longer: You can arrange the label, such as putting the Default label in front of all other labels. To illustrate it, I created an example and deliberately did not end the loop:

Switch (nsomething)

{

DEFAULT:

Case 5:

Goto Default;

}

I have retained one of the SWICH statement features until the end - in fact you can use a string as a constant expression. This for VB programmers may sound is not like an amazing news, but programmers from C or C will like this new feature.

Now, a SWITCH statement can be used as the string constant as shown below.

String strate = "chris";

Switch (strTest)

{

Case "Chris":

Console.writeline ("Hello Chris!");

Break;

}

6.2 circulating statement

When you want to repeat certain statements or quail, C # provides 4 different cyclic statements to you:

. For statement

. FOREACH statement

. WHILE statement

. DO statement

6.2.1 for statement

When you know how many statements should be performed in advance, the for statement is especially useful. When the condition is true, the conventional syntax allows repeatedly executed statements (and cyclic expressions):

FOR (initialization; condition; loop)

Note that initialization, conditions, and cycles are optional. If you have ignored the condition, you can generate a dead loop, to use the jump statement (BREAK or GOTO) to exit.

For (;;)

{

Break; // Due to certain reasons

}

Another focus, you can join multiple three parameters from multiplexed statements that are spaced apart from the FOR cycle. For example, you can initialize two variables, have three conditional statements, and repeat 4 variables. As a C or C programmer, you must understand only one change: the conditional statement must be a Boolean expression, just like the IF statement.

Listing 6.4 includes an example of using the for statement. It shows how to calculate a step, which is called fast than using a recursive function.

Listing 6.4 Calculate a step in the for loop

1: USING System;

2:

3: Class Factorial

4: {

5: public static void main (string [] args)

6: {

7: long nfactorial = 1;

8: long ncomputeto = int64.parse (args [0]);

9:

10: long ncurdig = 1;

11: for (ncurdig = 1; ncurdig <= ncomputeto; ncurdig )

12: nfactorial * = ncurdig;

13:

14: console.writeLine ("{0}! Is {1}", ncomputeto, nfactorial;

15:}

16:}

Although this example is too dragged, it uses an opening of a FOR statement. First, I should initialize internal declaration variable ncurdig:

For (Long nCurdig = 1; ncurdig <= ncomputeto; ncurdig ) nFactorial * = ncurdig;

Another choice to ignore the initialization is as follows, because the 10th line initializes the variable outside the FOR statement. (Remember that C # needs to initialize the variable):

For (; ncurdig <= ncomputeto; ncurdig ) nFactorial * = ncurdig;

Another change is to remove operations into the contents:

nfactorial * = nCurdig ; NFACTORIAL * = NCURDIG ;

If I want to get rid of the conditional statement, all to do what IF statement is added, and the loop is aborted by the BREAK statement:

For (;;)

{

IF (ncurdig> ncomputeto) Break;

nfactorial * = ncurdig ;

}

In addition to exiting the BREAK statement of the for statement, you can also skip the current loop with Continue and continue the next loop.

For (; ncurdig <= ncomputeto;)

{

IF (5 == ncurdig) Continue; // This line skips the rest of the code

nfactorial * = ncurdig ;

}

6.2.2 Foreach statement

One of the features that have been existed in the Visual Basic language is to enumerate collection by using the for Each statement. C # passes through the foreach statement, there is also a command to list the elements in the collection:

FOREACH (Type Identin Expressions) Contained statements

The loop variable is declared by type and identifier, and the expression corresponds to a collection. The loop variable represents a collection element that the loop is running.

You should know that you can't assign a new value to the loop variable, and you can't transfer it as a REF or OUT parameter. This references the code to be executed in the statement. How do you distinguish whether some classes support foreach statements? In short, classes must support methods with GetEnumerator () names, and the structure, class or interface returned by it must have a public method MoveNext () and public attribute Current. If you want to know more, please read the language reference manual, it has a lot of details about this topic.

For examples in Listing 6.5, I just selected a class to meet all of these requirements. I use it to list all environment variables defined.

Listing 6.5 Read all environment variables

1: USING System;

2: using system.collections;

3:

4: Class EnvironmentDumpApp

5: {

6: public static void main ()

7: {

8: idictionary envvars = Environment.GetenvironmentVariables ();

9: console.writeline ("there is {0} environment", envvars.keys.count);

10: Foreach (String strkey in envvars.keys)

11: {

12: console.writeLine ("{0} = {1}", strkey, envvars [strkey] .tostring ());

13:}

14:}

15:}

Returns an IDictionary type interface for the call (8th line) of GetEnvironmentvariables, which is a dictionary interface implemented in many classes in the .NET framework. With the IDictionary interface, you can access two sets: Keys and Values. In this example, I use KEYS in the foreach statement, then look for values ​​based on the current KEY value (line 12).

When using foreach, as long as one problem: When determining the type of the loop variable, be careful. Selecting the type of error is not detected by the compiler, but it will be detected at runtime and will trigger an exception.

6.2.3 While

When you want to perform an intrinsic statement 0 times or more, the While statement is what you look forward to:

WHILE (Condition)

Conditional statement - it is also a Boolean expression - the number of times the control is performed. You can use the Break and Continue statements to control the execution statements in the While statement, which is the same as in the For statement.

To illustrate the WHILE use, Listing 6.6 shows how to use a StreamReader class to output a C # source file to the screen.

Listing 6.6 shows the content of a file

1: USING System;

2: USING SYSTEM.IO;

3:

4: Class WhiLeDemoApp

5: {

6: public static void main ()

7: {

8: StreamReader SR = file.opentext ("whilesample.cs");

String strline = null;

10:

11: While (null! = (Strline = sr.readline ())))

12: {

13: console.writeline (strline);

14:}

15:

16: sr.close (); 17:}

18:}

The code opens the file whileSample.cs, then the read value is displayed on the screen when the Readline method returns a value that is not equal to NULL. Note that I use a assignment in the While condition statement. If there is more conditional statements that connect to && and ||, I can't guarantee whether they will be executed because there is a "short circuit".

6.2.4 DO statement

C # Latest cycle statement is a DO statement. It is very similar to the While statement, and the conditions are only verified after the initial cycle.

DO

{

Internal statement

}

While;

The DO statement guarantees that the contents are at least once, and as long as the condition evaluates is equal to true, they continue to be executed. By using the BREAK statement, you can force the run to exit the DO. If you want to skip this cycle, use the Continue statement.

An example of how to use the DO statement is displayed in Listing 6.7. It requests one or more numbers to the user, and calculates the average when the execution program exits the DO cycle.

Listing 6.7 Calculate the average in the DO loop

1: USING System;

2:

3: Class ComputeAvertApp

4: {

5: public static void main ()

6: {

7: computeaveRageapp theApp = new computeAVeApp ();

8: THEAPP.RUN ();

9: }

10:

11: Public void Run ()

12: {

13: double DVALUE = 0;

14: Double DSUM = 0;

15: int noofvalues ​​= 0;

16: char chcontinue = 'y';

17: String Strinput;

18:

19: do

20: {

21: Console.write ("Enter a value:");

22: STRINPUT = Console.readLine ();

23: DVALUE = double.parse (STRINPUT);

24: DSUM = DVALUE;

25: NnoofVALUES ;

26: Console.write ("Read Another Value?");

27:

28: STRINPUT = Console.readLine ();

29: chcontinue = char.fromstring (strINput);

30:}

31: While ('y' == chcontinue);

32:

33: Console.WriteLine ("The average is {0}", dsum / nnoofvalues;

34:}

35:}

In this example, I instantiate an object of the ComputeAvertApp type in the Static Main function. It also follows the RUN method of the instance, which contains all the necessary functions of the average.

The DO loop across the lines 19 ~ 31. The condition is set to set: Separates if each question is 'y' to decide whether to add another value. Enter any other characters can cause the program to exit the DO block and the average value is calculated.

As you can see from mentioned examples, the DO statement and the WHILE statement is not very different - only the difference is when the conditions are evaluated.

6.3 small knot

This chapter explains how to use the various selection and loop statements used in C #. The IF statement may be the most commonly used statement in the application. When using calculations in Boolean expressions, the compiler will pay attention to you. However, you must ensure that the "short circuit" of the conditional statement will not ignore the operation of the necessary code. Switch statement - although it is similar to the corresponding part of the C language - but also improved. Direct access is no longer supported, and you can use a string label for C programmers, this is a new usage.

The last part of this chapter, I explain how to use for, foreach, while and DO statements. The statement completes various needs, including the loop of the fixed number of times, enumerate the set elements and the statement to perform any number of any number of conditions based on certain conditions.

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

New Post(0)