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

C# 陳述式大全:從基本區塊到進階控制流程

     編輯:關於C語言

陳述式分類與範例

C# 陳述式多源自 C/C++,並有獨特增修。以下為完整分類:

區塊與標籤

// 區塊陳述式
static void Main() { F(); G(); { H(); I(); } }

// 標籤與 goto
static void Main(string[] args) {
    if (args.Length == 0) goto done;
    Console.WriteLine(args.Length);
done:
    Console.WriteLine("Done");
}

宣告陳述式

// 常數
const float pi = 3.14f;
const int r = 123;

// 區域變數
int a;
int b = 2, c = 3;
a = 1;

流程控制

// if-else
if (args.Length == 0) Console.WriteLine("無參數");
else Console.WriteLine("有參數");

// switch
switch (args.Length) {
    case 0: Console.WriteLine("無"); break;
    case 1: Console.WriteLine("一個"); break;
    default: Console.WriteLine("{0} 個", args.Length); break;
}

// while
while (i < args.Length) { Console.WriteLine(args[i]); i++; }

// do-while
do { s = Console.ReadLine(); } while (s != "Exit");

// for
for (int i = 0; i < args.Length; i++) Console.WriteLine(args[i]);

// foreach
foreach (string s in args) Console.WriteLine(s);

跳躍陳述式

// break 跳出迴圈
while (true) { if (i == args.Length) break; Console.WriteLine(args[i++]); }

// continue 跳過本次迴圈
while (true) { Console.WriteLine(args[i++]); if (i < args.Length) continue; break; }

// return
static int F(int a, int b) => a + b;

例外處理與資源管理

// try-catch-throw
try { Console.WriteLine(F(5, 0)); }
catch (Exception e) { Console.WriteLine("錯誤"); }

// checked/unchecked 溢位控制
int x = Int32.MaxValue;
checked { Console.WriteLine(x + 1); } // 拋出例外
unchecked { Console.WriteLine(x + 1); } // 靜默溢位

// lock 執行緒同步
lock (a) { a.P = a.P + 1; }

// using 自動釋放資源
using (Resource r = new Resource()) { r.F(); }

關鍵差異: C# 要求 if 條件必須為布林運算式,不可像 C/C++ 使用整數隱性轉換,避免 if (x = 5) 這類賦值誤寫成比較的常見錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved