C#表達式和語句


   表達式由操作數 (operand) 和運算符 (operator) 構成。表達式的運算符指示對操作數適用什么樣的運算。運算符的示例包括+、-、*、/ 和 new。操作數的示例包括文本、字段、局部變量和表達式。

  當表達式包含多個運算符時,運算符的優先級 (precedence) 控制各運算符的計算順序。例如,表達式 x + y * z 按 x + (y * z) 計算,因為 * 運算符的優先級高於 + 運算符。

  大多數運算符都可以重載 (overload)。運算符重載允許指定用戶定義的運算符實現來執行運算,這些運算的操作數中至少有一個,甚至所有操作數都屬於用戶定義的類類型或結構類型。

下表總結了 C# 運算符,並按優先級從高到低的順序列出各運算符類別。同一類別中的運算符優先級相同。

 

類別

表達式

說明

基本

x.m

成員訪問

x(...)

方法和委托調用

x[...]

數組和索引器訪問

x++

后增量

x--

后減量

new T(...)

對象和委托創建

new T(...){...}

使用初始值設定項創建對象

new {...}

匿名對象初始值設定項

new T[...]

數組創建

typeof(T)

獲取 T 的 System.Type 對象

checked(x)

在 checked 上下文中計算表達式

unchecked(x)

在 unchecked 上下文中計算表達式

default(T)

獲取類型 T 的默認值

delegate {...}

匿名函數(匿名方法)

一元

+x

恆等

-x

求相反數

!x

邏輯求反

~x

按位求反

++x

前增量

--x

前減量

(T)x

將 x 顯式轉換為類型 T

await x

異步等待 x 完成

乘法

x * y

乘法

x / y

除法

x % y

求余

 

加減

x + y

加法、字符串串聯、委托組合

x – y

減法、委托移除

移位

x << y

左移

x >> y

右移

關系和類型檢測

x < y

小於

x > y

大於

x <= y

小於或等於

x >= y

大於或等於

x is T

如果 x 為 T,則返回 true,否則返回 false

x as T

返回轉換為類型 T 的 x,如果 x 不是 T 則返回 null

相等

x == y

等於

x != y

不等於

邏輯“與”

x & y

整型按位 AND,布爾邏輯 AND

邏輯 XOR

x ^ y

整型按位 XOR,布爾邏輯 XOR

邏輯 OR

x | y

整型按位 OR,布爾邏輯 OR

條件 AND

x && y

僅當 x 為 true 時,才對 y 求值

條件 OR

x || y

僅當 x 為 false 時,才對 y 求值

null 合並

X ?? y

如果 x 為 null,則計算結果為 y,否則計算結果為 x

條件

x ? y : z

如果 x 為 true,則對 y 求值;如果 x 為 false,則對 z 求值

賦值或匿名函數

x = y

賦值

x op= y

復合賦值;支持的運算符有:

*=   /=   %=   +=   -=   <<=   >>=   &=   ^=   |=

(T x) => y

匿名函數(lambda 表達式)

  語句

  程序的操作是使用語句 (statement) 來表示的。C# 支持幾種不同的語句,其中許多以嵌入語句的形式定義。

  block 用於在只允許使用單個語句的上下文中編寫多條語句。塊由位於一對大括號 { 和 } 之間的語句列表組成。

  聲明語句 (declaration statement) 用於聲明局部變量和常量。

  表達式語句 (expression statement) 用於對表達式求值。可用作語句的表達式包括方法調用、使用 new 運算符的對象分配、使用 = 和復合賦值運算符的賦值、使用 ++ 和 -- 運算符的增量和減量運算以及 await 表達式。

  選擇語句 (selection statement) 用於根據表達式的值從若干個給定的語句中選擇一個來執行。這一組中有 if 和 switch 語句。

  迭代語句 (iteration statement) 用於重復執行嵌入語句。這一組中有 while、do、for 和 foreach 語句。

  跳轉語句 (jump statement) 用於轉移控制。這一組中有 break、continue、goto、throw、return 和 yield 語句。

  try...catch 語句用於捕獲在塊的執行期間發生的異常,try...finally 語句用於指定終止代碼,不管是否發生異常,該代碼都始終要執行。

  checked 語句和 unchecked 語句用於控制整型算術運算和轉換的溢出檢查上下文。

  lock 語句用於獲取某個給定對象的互斥鎖,執行一個語句,然后釋放該鎖。

  using 語句用於獲得一個資源,執行一個語句,然后釋放該資源。

  下表列出了 C# 的各語句,並提供每個語句的示例。

語句

示例

局部變量聲明

static void Main() {
    int a;
    int b = 2, c = 3;
    a = 1;
    Console.WriteLine(a + b + c);
}

局部常量聲明

static void Main() {
    const float pi = 3.1415927f;
    const int r = 25;
    Console.WriteLine(pi * r * r);
}

表達式語句

static void Main() {
    int i;
    i = 123;                    // Expression statement
    Console.WriteLine(i);    // Expression statement
    i++;                        // Expression statement
    Console.WriteLine(i);    // Expression statement
}

if語句

static void Main(string[] args) {
    if (args.Length == 0) {
       Console.WriteLine("No arguments");
    }
    else {
       Console.WriteLine("One or more arguments");
    }
}

 

switch語句

static void Main(string[] args) {
    int n = args.Length;
    switch (n) {
       case 0:
           Console.WriteLine("No arguments");
           break;
       case 1:
           Console.WriteLine("One argument");
           break;
       default:
           Console.WriteLine("{0} arguments", n);
           break;
       }
    }
}

while語句

static void Main(string[] args) {
    int i = 0;
    while (i < args.Length) {
       Console.WriteLine(args[i]);
       i++;
    }
}

do語句

static void Main() {
    string s;
    do {
       s = Console.ReadLine();
       if (s != null) Console.WriteLine(s);
    } while (s != null);
}

for語句

static void Main(string[] args) {
    for (int i = 0; i < args.Length; i++) {
       Console.WriteLine(args[i]);
    }
}

foreach語句

static void Main(string[] args) {
    foreach (string s in args) {
       Console.WriteLine(s);
    }
}

break語句

static void Main() {
    while (true) {
       string s = Console.ReadLine();
       if (s == null) break;
       Console.WriteLine(s);
    }
}

continue語句

static void Main(string[] args) {
    for (int i = 0; i < args.Length; i++) {
       if (args[i].StartsWith("/")) continue;
       Console.WriteLine(args[i]);
    }
}

 

goto語句

static void Main(string[] args) {
    int i = 0;
    goto check;
    loop:
    Console.WriteLine(args[i++]);
    check:
    if (i < args.Length) goto loop;
}

return語句

static int Add(int a, int b) {
    return a + b;
}

static void Main() {
    Console.WriteLine(Add(1, 2));
    return;
}

yield語句

static IEnumerable<int> Range(int from, int to) {
    for (int i = from; i < to; i++) {
       yield return i;
    }
    yield break;
}

static void Main() {
    foreach (int x in Range(-10,10)) {
       Console.WriteLine(x);
    }
}

throw 和 try
 語句

static double Divide(double x, double y) {
    if (y == 0) throw new DivideByZeroException();
    return x / y;
}

static void Main(string[] args) {
    try {
       if (args.Length != 2) {
           throw new Exception("Two numbers required");
       }
       double x = double.Parse(args[0]);
       double y = double.Parse(args[1]);
       Console.WriteLine(Divide(x, y));
    }
    catch (Exception e) {
       Console.WriteLine(e.Message);
    }
    finally {
       Console.WriteLine(“Good bye!”);
    }
}

checked 和 unchecked 語句

static void Main() {
    int i = int.MaxValue;
    checked {
       Console.WriteLine(i + 1);       // Exception
    }
    unchecked {
       Console.WriteLine(i + 1);       // Overflow
    }
}

 

lock語句

class Account
{
    decimal balance;

    public void Withdraw(decimal amount) {
       lock (this) {
           if (amount > balance) {
              throw new Exception("Insufficient funds");
           }
           balance -= amount;
       }
    }
}

using語句

static void Main() {
    using (TextWriter w = File.CreateText("test.txt")) {
       w.WriteLine("Line one");
       w.WriteLine("Line two");
       w.WriteLine("Line three");
    }
}

 

 



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM