小编SHE*_*NeP的帖子

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

我有以下课程:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:我可以检查Value是否为真,没有== true?操作员覆盖有效,但是我也可以这样使用它吗?

InterlockedBool ib = new InterlockedBool();
if (ib) { }
Run Code Online (Sandbox Code Playgroud)

而不是(这有效,但通常我省略了== true …

c# overriding class operators

7
推荐指数
2
解决办法
472
查看次数

标签 统计

c# ×1

class ×1

operators ×1

overriding ×1