如果(实例)/自定义的隐式布尔转换 class

If (instance) / implicit boolean conversion on a custom class

我有以下 class:

public class InterlockedBool
{
    private int _value;

    public bool Value
    {
        get { return _value > 0; }
        set { System.Threading.Interlocked.Exchange(ref _value, value ? 1 : 0); }
    }

    public static bool operator ==(InterlockedBool obj1, bool obj2)
    {
        return obj1.Value.Equals(obj2);
    }
    public static bool operator !=(InterlockedBool obj1, bool obj2)
    {
        return !obj1.Value.Equals(obj2);
    }
    public override bool Equals(bool obj)
    {
        return this.Value.Equals(obj);
    }
}

我的问题是:我可以在没有 == true 的情况下检查 Value 是否为真吗?运算符覆盖有效,但我也可以这样使用它吗?

InterlockedBool ib = new InterlockedBool();
if (ib) { }

而不是(这有效,但通常我在 if 语句中省略 == true

if (ib == true) { }
  1. 以及如何在不使用的情况下将其分配给一个值 .Value =

谢谢你的帮助:)

您可以定义到 bool 的隐式转换:

public static implicit operator bool(InterlockedBool obj)
{
    return obj.Value;
}

您需要能够将您的对象 转换为 布尔值

隐式转换

您对布尔值的对象:

public static implicit operator bool(InterlockedBool obj)
{
    return obj.Value;
}

然后是对象的布尔值:

public static implicit operator InterlockedBool(bool obj)
{
    return new InterlockedBool(obj);
}

那你可以测试一下:

InterlockedBool test1 = true;
if (test1)
{
    //Do stuff
}

显式转换

如果您希望此 class 的用户知道正在发生转换,您可以强制进行显式转换:

public static explicit operator bool(InterlockedBool obj)
{
    return obj.Value;
}

public static explicit operator InterlockedBool(bool obj)
{
    return new InterlockedBool(obj);
}

那么你必须显式地转换你的对象:

InterlockedBool test1 = (InterlockedBool)true;
if ((bool)test1)
{
    //Do stuff
}

编辑(由于 OP 评论)

在从布尔值到你的对象的转换中,我调用了一个你没有提到的构造函数,下面是我将如何构建它:

public InterlockedBool(bool Value)
{
    this.Value = Value;
}

因此该值的设置保证线程安全