# true 和 false 運算子 (C# 參考)

true運算子會傳回布林值， true 以指出其運算元絕對為 true。 false運算子 bool 會傳回值， true 以指出其運算元絕對為 false。 truefalse 運算子並不保證會彼此互補。 也就是說，truefalse 運算子可能會針對相同的運算元傳回 boolfalse。 如果某個型別會定義這兩個運算子之一，它也必須定義另一個運算子。

bool?如果您需要支援三值邏輯 (例如，當您使用支援三值布林值類型的資料庫時，請使用類型) 。 C# 能提供搭配 bool? 運算元來支援三值邏輯的 &| 運算子。 如需詳細資訊，請參閱布林邏輯運算子一文的可為 Null 的布林邏輯運算子一節。

## 範例

using System;

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;
}

{

Getting fuel launch status...