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

C# 語法練習 (3):運算子優先序與實戰技巧

     編輯:關於C#

C# 運算子完整分類與實務範例

熟悉運算子優先序與特殊行為能避免邏輯錯誤並寫出高效程式碼。本文涵蓋算術、位元、邏輯、條件、Lambda 等全類別運算子並附實戰範例。

一、運算子優先序速查表(由高到低)

基本:      . () [] x++ x-- new typeof checked unchecked -> ::
一元:      + - ! ~ ++x --x (T)x true false & sizeof
乘除:      * / %
加減:      + -
移位:      << >>
關系:      < > <= >= is as
相等:      == !=
邏輯 AND:  &
邏輯 XOR:  ^
邏輯 OR:   |
條件 AND:  &&
條件 OR:   ||
條件選擇:  ?: ??
賦值:      = += -= *= /= %= &= |= ^= <<= >>=
Lambda:    =>

二、整數除法陷阱

整數 / 整數 = 整數,小數部份直接捨棄。

using System;

class MyClass
{
    static void Main()
    {
        double d;
        d = 14 / 4;       // 3 (整數除法)
        Console.WriteLine(d); 
        d = 14 / 4.0;     // 3.5
        Console.WriteLine(d);
        d = 14.0 / 4.0;   // 3.5
        Console.WriteLine(d);
        d = 14.0 / 4;     // 3.5
        Console.WriteLine(d);

        Console.WriteLine();

        float f;
        f = 14 / 4;                  // 3
        Console.WriteLine(f);
        f = (float)(14.0 / 4.0);     // 3.5 (預設 double 需轉型)
        Console.WriteLine(f);

        Console.WriteLine();

        int i;
        i = 14 / 4;        // 3
        Console.WriteLine(i);
        i = (int)(14.0 / 4.0); // 3
        Console.WriteLine(i);
        i = 14 % 4;        // 2 (餘數)
        Console.WriteLine(i);

        Console.ReadKey();
    }
}

三、++ / -- 適用於浮點數

using System;

class MyClass
{
    static void Main()
    {
        double f = 1.5;
        f++; Console.WriteLine(f); // 2.5
        f--; Console.WriteLine(f); // 1.5
        Console.WriteLine(++f);    // 2.5 (前置遞增)
        Console.WriteLine(--f);    // 1.5 (前置遞減)

        Console.ReadKey();
    }
}

四、條件運算子 ?:

using System;

class MyClass
{
    static void Main()
    {
        int n, a = 11, b = 22;

        n = a > b ? a : b; // 22
        Console.WriteLine(n);
        n = a < b ? a : b; // 11
        Console.WriteLine(n);

        Console.ReadKey();
    }
}

五、Null 聯合運算子 ??

用於可為 null 的實值型別(int?、bool? 等),左運算元為 null 時回傳右運算元。

using System;

class MyClass
{
    static void Main()
    {
        int? x = null;
        int y;

        y = x ?? -1; // x 為 null,回傳 -1
        Console.WriteLine(y); // -1

        x = 9;
        y = x ?? -1; // x 不為 null,回傳 9
        Console.WriteLine(y); // 9

        Console.ReadKey();
    }
}

六、Lambda 運算子 =>

搭配 LINQ 進行查詢與轉換。

using System;
using System.Linq;

class MyClass
{
    static void Main()
    {
        int n1, n2;

        int[] ns = { 22, 333, 4444, 9 };
        n1 = ns.Max(num => num);
        n2 = ns.Min(num => num);
        Console.WriteLine("{0}, {1}", n1, n2); // 4444, 9

        string[] ss = { "aaa", "bbbb", "ccccc", "dd" };
        n1 = ss.Max(str => str.Length);
        n2 = ss.Min(str => str.Length);
        Console.WriteLine("{0}, {1}", n1, n2); // 5, 2

        Console.ReadKey();
    }
}

七、位元邏輯運算子 & | ^ !

using System;

class MyClass
{
    static void Main()
    {
        bool b;
        b = true & true;   Console.WriteLine(b); // True
        b = true & false;  Console.WriteLine(b); // False
        b = false & false; Console.WriteLine(b); // False

        b = true | true;   Console.WriteLine(b); // True
        b = true | false;  Console.WriteLine(b); // True
        b = false | false; Console.WriteLine(b); // False

        b = true ^ true;   Console.WriteLine(b); // False
        b = true ^ false;  Console.WriteLine(b); // True
        b = false ^ false; Console.WriteLine(b); // False

        b = !true;  Console.WriteLine(b); // False
        b = !false; Console.WriteLine(b); // True

        Console.ReadKey();
    }
}

八、短路邏輯運算子 && ||

條件判斷時優先使用 &&、||,具備短路特性:左運算元已能決定結果時,不評估右運算元,效能更佳且避免副作用。

using System;

class MyClass
{
    static void Main()
    {
        bool b;

        // && 短路:左側 false 則不評估右側
        b = false && true;  Console.WriteLine(b); // False
        b = false && false; Console.WriteLine(b); // False
        b = true && true;   Console.WriteLine(b); // True
        b = true && false;  Console.WriteLine(b); // False

        // || 短路:左側 true 則不評估右側
        b = true || true;   Console.WriteLine(b); // True
        b = true || false;  Console.WriteLine(b); // True
        b = false || true;  Console.WriteLine(b); // True
        b = false || false; Console.WriteLine(b); // False

        Console.ReadKey();
    }
}

重點提醒

  • 整數除法會捨棄小數,需至少一個運算元為浮點數才得浮點結果。
  • &、| 不具短路特性,&&、|| 具短路,條件判斷請用後者。
  • ?? 僅適用於可為 null 的實值型別或參考型別。
  • Lambda 運算子 => 是 LINQ 與委派簡寫的核心語法。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved