首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 語法練習 (5):控制流程陳述式總覽

     編輯:關於C#

C# 控制流程陳述式速查表

掌握條件判斷、迴圈與跳躍陳述式是撰寫高品質 C# 程式的基礎。本文整理所有核心語法並附上 switch 字串比較的實務技巧。

一、核心語法一覽

// 條件判斷
if (bool) { } else { }

switch (v) 
{ 
    case v1: ... break; 
    case v2: ... break; 
    default: ... break; 
}

// 迴圈
do { } while (bool);
while (bool) { }
for (int i = 0; i < 10; i++) { }
foreach (Type item in items) { }

// 跳躍
break;
continue;
goto Label; // 需搭配標籤使用

二、switch 陳述式支援字串比較

C# 的 switch 原生支援字串,但 case 標籤必須為編譯期常數(const string),不可使用變數。

using System;

class MyClass
{
    static void Main()
    {
        string[] str = { "a", "bb", "ccc" };

        // 必須使用 const string
        const string s1 = "bb";
        const string s2 = "ccc";

        foreach (string s in str)
        {
            switch (s)
            {
                case s1: Console.WriteLine(s.Length); break; // 輸出 2
                case s2: Console.WriteLine(s.Length); break; // 輸出 3
                default: Console.WriteLine(s); break;        // 輸出 "a"
            }
        }

        Console.ReadKey();
    }
}

三、實務建議

  • if-else:適合少數條件或複雜布林運算式。
  • switch:適用於單一變數對多個常數值比對,效能較佳且可讀性高。
  • foreach:遍歷集合首選,避免索引越界風險。
  • goto:極少使用,僅在巢狀迴圈跳脫或狀態機實作時考慮。
  • switch 的 case 必須為 const,C# 7.0+ 可使用 pattern matching 擴展功能(如 case int n when n > 0:)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved