为什么当第一个操作数为false时重载的'&'运算符不会触发?

时间:2020-05-23 10:45:53

标签: c# operator-overloading operators operator-keyword

我需要一个奇怪的类,该类可以帮助我制作复杂的谓词并存储组件,这将在另一种情况下对我有帮助。

我的问题是,当我重载“&”运算符(当然还有true和false运算符)时,我的“&”运算符在某些情况下不会触发。

public class ObservablePredicate // : IObservable<bool> does not need now
{
    public ObservablePredicate Parent { get; set; }
    public IList<ObservablePredicate> Components { get; set; }

    public static bool operator true(ObservablePredicate x)
    {
        return x.Value;
    }

    public static bool operator false(ObservablePredicate x)
    {
        return !x.Value;
    }

    public static ObservablePredicate operator &(ObservablePredicate a, ObservablePredicate b)
    {
        if (a == null) a = new ObservablePredicate(false);
        if (b == null) b = new ObservablePredicate(false);

        var result = a.Value && b.Value;
        return new ObservablePredicate(result, a, b);
    }

    private bool _value;
    public bool Value
    {
        get => _value;
        set
        {
            _value = value;
            // do something with components if exists...
            // do something with parent if exists...
        }
    }

    public ObservablePredicate(ObservablePredicate p)
    {
        Initialise(p.Value, null);
    }

    public ObservablePredicate(bool value, params ObservablePredicate[] predicates)
    {
        predicates.ToList().ForEach(p => p.Parent = this);
        Initialise(value, predicates.ToList());
    }

    private void Initialise(bool value, List<ObservablePredicate> components)
    {
        Components = components ?? new List<ObservablePredicate>();
        Value = value;
    }
}

在以下情况下,“&”运算符会触发:

var prediacteA = new ObservablePredicate(true);
var predicateB = new ObservablePredicate(true);
var predicateC = prediacteA && predicateB;
var prediacteA = new ObservablePredicate(true);
var predicateB = new ObservablePredicate(false);
var predicateC = prediacteA && predicateB;

但在以下情况下不会出现,因此我的Components属性将为空:

var prediacteA = new ObservablePredicate(false);
var predicateB = new ObservablePredicate(true);
var predicateC = prediacteA && predicateB;
var prediacteA = new ObservablePredicate(false);
var predicateB = new ObservablePredicate(false);
var predicateC = prediacteA && predicateB;

我该如何解决?

1 个答案:

答案 0 :(得分:3)

根据this&&个操作符不能重载。

&是一个逻辑AND,其中&&是一个条件逻辑运算符,也称为短路,这意味着如果第一个条件为假,它将不评估第二个条件。

通常,在if语句和其他谓词中始终使用&&,在按位操作时通常使用&

if(a && b) // where a and b is booleans

0b0101 & 0b0100 = 0b0100