// Change the values of these variables to test the results. bool Condition1 = true; bool Condition2 = true; bool Condition3 = true; bool Condition4 = true;
if (Condition1) { // Condition1 is true. } elseif (Condition2) { // Condition1 is false and Condition2 is true. } elseif (Condition3) { if (Condition4) { // Condition1 and Condition2 are false. Condition3 and Condition4 are true. } else { // Condition1, Condition2, and Condition4 are false. Condition3 is true. } } else { // Condition1, Condition2, and Condition3 are false. }
publicclassExample { publicstaticvoidMain() { int caseSwitch = 1;
switch (caseSwitch) { case1: Console.WriteLine("Case 1"); break; case2: Console.WriteLine("Case 2"); break; default: Console.WriteLine("Default case"); break; } } } // The example displays the following output: // Case 1
开关部分
C# 不允许从一个开关部分继续执行到下一个开关部分。 因此,以下代码将生成编译器错误。
error CS0163: 控制不能从一个 case 标签(“case 1:”)贯穿到另一个 case 标 签
1 2 3 4 5 6 7 8 9 10
switch (caseSwitch) { // The following switch section causes an error. case1: Console.WriteLine("Case 1..."); // Add a break or other jump statement here. case2: Console.WriteLine("... and/or Case 2"); break; }
default case
default case 可以在 switch 语句中以任何顺序显示。 无论其在源代码中的顺序如何,都将在对所有 case 标签进行计算之后,最后对其进行计算。
classProgram { staticvoidMain() { switch (DateTime.Now.DayOfWeek) { case DayOfWeek.Sunday: case DayOfWeek.Saturday: Console.WriteLine("The weekend"); break; case DayOfWeek.Monday: Console.WriteLine("The first day of the work week."); break; case DayOfWeek.Friday: Console.WriteLine("The last day of the work week."); break; default: Console.WriteLine("The middle of the work week."); break; } } } // The example displays output like the following: // The middle of the work week.
privatestaticvoidShowCollectionInformation(object coll) { switch (coll) { case Array arr: Console.WriteLine($"An array with {arr.Length} elements."); break; case IEnumerable<int> ieInt: Console.WriteLine($"Average: {ieInt.Average(s => s)}"); break; case IList list: Console.WriteLine($"{list.Count} items"); break; case IEnumerable ie: string result = ""; foreach (var item in ie) result += "${e} "; Console.WriteLine(result); break; casenull: // Do nothing for a null. break; default: Console.WriteLine($"A instance of type {coll.GetType().Name}"); break; } } } // The example displays the following output: // An array with 5 elements. // 4 items
case 语句和 when 子句
从 C# 7 开始,因为 case 语句不需要互相排斥,因此可以添加 when 子句来指定必须满足的附加条件使 case 语句计算为 true。 when 子句可以是返回布尔值的任何表达式。 when 子句的更常见用法之一是防止在匹配表达式的值为 null 时执行开关部分。
classWhileTest { staticvoidMain() { int n = 1; while (n < 6) { Console.WriteLine("Current value of n is {0}", n); n++; } } } /* Output: Current value of n is 1 Current value of n is 2 Current value of n is 3 Current value of n is 4 Current value of n is 5 */
因为 while 表达式的测试在每次执行循环之前开始,所以 while 循环执行零次或多次。 这不同于 do 循环,该循环执行一次或多次。
int[] fibarray = newint[] { 0, 1, 1, 2, 3, 5, 8, 13 }; // Compare the previous loop to a similar for loop. for (int i = 0; i < fibarray.Length; i++) { System.Console.WriteLine(fibarray[i]); } System.Console.WriteLine(); // Output: // 0 // 1 // 1 // 2 // 3 // 5 // 8 // 13
维护数组中元素数计数的 foreach 循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int[] fibarray = newint[] { 0, 1, 1, 2, 3, 5, 8, 13 }; // You can maintain a count of the elements in the collection. int count = 0; foreach (int element in fibarray) { count += 1; System.Console.WriteLine("Element #{0}: {1}", count, element); } System.Console.WriteLine("Number of elements in the array: {0}", count); // Output: // Element #1: 0 // Element #2: 1 // Element #3: 1 // Element #4: 2 // Element #5: 3 // Element #6: 5 // Element #7: 8 // Element #8: 13 // Number of elements in the array: 8
因为 while 表达式的测试在每次执行循环之前开始,所以 while 循环执行零次或多次。 这不同于 do 循环,该循环执行一次或多次。
// Outer loop for (int x = 0; x < numbers.Length; x++) { Console.WriteLine("num = {0}", numbers[x]);
// Inner loop for (int y = 0; y < letters.Length; y++) { if (y == x) { // Return control to outer loop break; } Console.Write(" {0} ", letters[y]); } Console.WriteLine(); }
// Keep the console open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } }
/* * Output: num = 0 num = 1 a num = 2 a b num = 3 a b c num = 4 a b c d num = 5 a b c d e num = 6 a b c d e f num = 7 a b c d e f g num = 8 a b c d e f g h num = 9 a b c d e f g h i */
classSwitchTest { staticvoidMain() { Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large"); Console.Write("Please enter your selection: "); string s = Console.ReadLine(); int n = int.Parse(s); int cost = 0; switch (n) { case1: cost += 25; break; case2: cost += 25; gotocase1; case3: cost += 50; gotocase1; default: Console.WriteLine("Invalid selection."); break; } if (cost != 0) { Console.WriteLine("Please insert {0} cents.", cost); } Console.WriteLine("Thank you for your business.");
// Keep the console open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Sample Input: 2 Sample Output: Coffee sizes: 1=Small 2=Medium 3=Large Please enter your selection: 2 Please insert 50 cents. Thank you for your business. */
// Read input: Console.Write("Enter the number to search for: ");
// Input a string: string myNumber = Console.ReadLine();
// Search: for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { if (array[i, j].Equals(myNumber)) { goto Found; } } }
Console.WriteLine("The number {0} was not found.", myNumber); goto Finish;
Found: Console.WriteLine("The number {0} is found.", myNumber);
Finish: Console.WriteLine("End of search.");
// Keep the console open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Sample Input: 44 Sample Output Enter the number to search for: 44 The number 44 is found. End of search. */
classMainClass { staticvoidMain() { #line 200 "Special" int i; // CS0168 on line 200 int j; // CS0168 on line 201 #line default char c; // CS0168 on line 9 float f; // CS0168 on line 10 #line hidden // numbering not affected string s; double d; // CS0168 on line 13 } }