What's the false operator in C# good for?

前端 未结 5 1559
無奈伤痛
無奈伤痛 2020-11-30 18:21

There are two weird operators in C#:

  • the true operator
  • the false operator

If I understand this right these operators can be used in typ

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 18:52

    You can use it to override the && and || operators.

    The && and || operators can't be overridden, but if you override |, &, true and false in exactly the right way the compiler will call | and & when you write || and &&.

    For example, look at this code (from http://ayende.com/blog/1574/nhibernate-criteria-api-operator-overloading - where I found out about this trick; archived version by @BiggsTRC):

    public static AbstractCriterion operator &(AbstractCriterion lhs, AbstractCriterion rhs)
    {
           return new AndExpression(lhs, rhs);
    }
    
    public static AbstractCriterion operator |(AbstractCriterion lhs, AbstractCriterion rhs)
    {
           return new OrExpression(lhs, rhs);
    }
    
    public static bool operator false(AbstractCriterion criteria)
    {
           return false;
    }
    public static bool operator true(AbstractCriterion criteria)
    {
           return false;
    }
    

    This is obviously a side effect and not the way it's intended to be used, but it is useful.

提交回复
热议问题