true 和 false 运算符 - 将对象视为布尔值

true 运算符返回 booltrue 来指示其操作数一定为 true,而 false 运算符则返回 booltrue 来指示其操作数一定为 false。
请注意,同时实现 truefalse 运算符的类型必须遵循以下语义:

  • “此对象是否为 true?”解析为运算符 true。 如果对象为 true,运算符 true 将返回 true。 应答为“是,此对象为 true”。
  • “此对象是否为 false?”解析为运算符 false。 如果对象为 false,运算符 false 将返回 true。 应答为“是,此对象为 false”

无法确保 truefalse 运算符互补。 也就是说,truefalse 运算符可能同时针对同一个操作数返回 boolfalse。 如果某类型定义这两个运算符之一,则其还必须定义另一个运算符。

提示

如需支持三值逻辑(例如,在使用支持三值布尔类型的数据库时),请使用 bool? 类型。 C# 提供 &| 运算符,它们通过 bool? 操作数支持三值逻辑。 有关详细信息,请参阅布尔逻辑运算符一文的可以为 null 的布尔逻辑运算符部分。

布尔表达式

包含已定义 true 运算符的类型可以是 ifdowhilefor 语句以及条件运算符 ?: 中控制条件表达式的结果的类型。 有关详细信息,请参阅 C# 语言规范中的 Boolean 表达式部分。

用户定义的条件逻辑运算符

如果包含已定义 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 时,不会进行计算的 && 运算符的右侧操作数。 这是因为 LaunchStatus.Red 一定为 false。 然后,逻辑 AND 运算符的结果不依赖右侧操作数的值。 示例的输出如下所示:

Getting fuel launch status...
Wait!

另请参阅