共用方式為


真與假算子

true 運算子會傳回 booltrue,表示其運算元肯定為 true,而 false 運算子會傳回 booltrue,表示其運算元肯定為 false。

C# 語言參考資料記錄了 C# 語言最新版本。 同時也包含即將推出語言版本公開預覽功能的初步文件。

文件中標示了語言最近三個版本或目前公開預覽版中首次引入的任何功能。

提示

欲查詢某功能何時首次在 C# 中引入,請參閱 C# 語言版本歷史的條目。

同時實 true 作 和 false 運算子的型別必須遵循以下語意:

  • "Is this object true?" 解析為運算子 true。 如果物件是 true,運算子 true 會傳回 true。 答案為 "Yes, this object is true"。
  • “this object false?” 解析為運算子 false。 如果物件是 false,運算子 true 會傳回 false。 答案是「是的,這個物件是假的」。

truefalse 運算子不保證會彼此互補。 也就是說,truefalse 運算子可能會針對相同的運算元傳回 boolfalse。 如果某個型別定義這兩個運算子之一,也必須定義另一個運算子。

提示

如果你需要支援三值邏輯(例如,當你處理支援三值布林型態的資料庫時),請使用該 bool? 類型。 C# 提供&|與運算元,支援三bool?值邏輯的運算子。 如需詳細資訊,請參閱布林值邏輯運算子一文的可為 Null 的布林值邏輯運算子一節。

布林運算式

具有已定義 true 運算子的型別可以是 ifdowhilefor 陳述式,以及條件運算子 ?:中之控制條件運算式的結果型別。 如需詳細資訊,請參閱 C# 語言規格布林運算式一節。

使用者定義條件式邏輯運算子

如果具有已定義 truefalse 運算子的型別以某種方式多載邏輯 OR 運算子|邏輯 AND 運算子&,系統可以針對該型別的運算元分別評估條件邏輯 OR 運算子||條件邏輯 AND 運算子&&。 如需詳細資訊,請參閱 C# 語言規格使用者定義條件式邏輯運算子一節。

範例

下列範例顯示同時定義了 truefalse 運算子的型別。 型別也會以超載方式使邏輯 AND 運算子&&&得以對該型態的運算元進行評估。

public struct LaunchStatus
{
    public static readonly LaunchStatus Green = new LaunchStatus(0);
    public static readonly LaunchStatus Yellow = new LaunchStatus(1);
    public static readonly LaunchStatus Red = new LaunchStatus(2);

    private int status;

    private LaunchStatus(int status)
    {
        this.status = status;
    }

    public static bool operator true(LaunchStatus x) => x == Green || x == Yellow;
    public static bool operator false(LaunchStatus x) => x == Red;

    public static LaunchStatus operator &(LaunchStatus x, LaunchStatus y)
    {
        if (x == Red || y == Red || (x == Yellow && y == Yellow))
        {
            return Red;
        }

        if (x == Yellow || y == Yellow)
        {
            return Yellow;
        }

        return Green;
    }

    public static bool operator ==(LaunchStatus x, LaunchStatus y) => x.status == y.status;
    public static bool operator !=(LaunchStatus x, LaunchStatus y) => !(x == y);

    public override bool Equals(object obj) => obj is LaunchStatus other && this == other;
    public override int GetHashCode() => status;
}

public class LaunchStatusTest
{
    public static void Main()
    {
        LaunchStatus okToLaunch = GetFuelLaunchStatus() && GetNavigationLaunchStatus();
        Console.WriteLine(okToLaunch ? "Ready to go!" : "Wait!");
    }

    static LaunchStatus GetFuelLaunchStatus()
    {
        Console.WriteLine("Getting fuel launch status...");
        return LaunchStatus.Red;
    }

    static LaunchStatus GetNavigationLaunchStatus()
    {
        Console.WriteLine("Getting navigation launch status...");
        return LaunchStatus.Yellow;
    }
}

請注意 && 運算子的最少運算行為。 當 GetFuelLaunchStatus 方法傳回 LaunchStatus.Red 時,系統並不會評估 && 運算子的右邊運算元。 這個條件絕對是錯誤的。 邏輯 AND 的結果不依賴於右手運算元的值。 此範例的輸出如下:

Getting fuel launch status...
Wait!

另請參閱