使 false 和 true 运算符重载无法正常工作

Troubles getting false and true operator overload to work

假设我们有以下代码:

class A {
    public B b { get; set; }
}

class B {
    int x;
    public static bool operator true(B d1)
    {
        return d1.x > 0;
    }

    public static bool operator false(B d1)
    {
        return !(d1.x > 0);
    }
}

现在,我正在尝试做这样的事情:

//A a1, a2;
if(a1.b || ( a2 != null && a2.b))

但是,我收到一条错误消息,指出不能在 bool 类型和 "B" 类型之间使用 &&。好像 bool 运算符不适用于 a2.b 表达式。有人知道怎么回事吗?

我会以稍微不同的方式编写它以使其正常工作。您只需要重载隐式 bool 运算符(并确保 A.b 不为空):

class A {
    A() { b = new B();}
    public B b { get; set; }
}
class B {
    int x;
    public static implicit operator bool(B d1) {
        return d1.x > 0;
    }
}

我认为您还需要重载一些额外的运算符才能使其按预期工作。查看 this MSDN example

class A
{
    public B b { get; set; }
}

class B
{
    int x;

    public static implicit operator B(bool b) 
    {
        return b ? new B { x = 1 } : new B { x = 0 };
    }

    public static explicit operator bool(B b)
    {
        return b.x > 0;
    }

    public static bool operator true(B d1)
    {
        return d1.x > 0;
    }

    public static bool operator false(B d1)
    {
        return !(d1.x > 0);
    }

    public static B operator &(B d1, B d2) 
    {
        return d1.x > 0 && d2.x > 0;
    }

    public static B operator |(B d1, B d2)
    {
        return d1.x > 0 || d2.x > 0;
    }
}

那么你可以这样做:

static void Main()
{
    var a1 = new A();
    var a2 = new A();
    if (a1.b || (a2 != null && a2.b))
    {

    }
}

请注意,由于 类 AB 的范围有限,我不确定如何实际处理重载,所以我做了一些假设。无论如何,前提是为您准备的。这是工作代码的.NET fiddle