Why overload true and false instead of defining bool operator?

前端 未结 4 1784
孤城傲影
孤城傲影 2021-02-01 06:31

I\'ve been reading about overloading true and false in C#, and I think I understand the basic difference between this and defining a bool operator. The example I see around is

相关标签:
4条回答
  • 2021-02-01 07:16

    I had no idea these operators existed. That means you can implement the self-negation paradox:

    public class ThisClassIsFalse
    {
        public static bool operator true(ThisClassIsFalse statement)
        {
            return statement ? false : true;
        }
    
        public static bool operator false(ThisClassIsFalse statement)
        {
            return statement ? true : false;
        }
    }
    

    So now we know the true solution to this classic paradox... StackOverflowException.

    0 讨论(0)
  • As the docs say, overloading true and false is intended to support (nullable) database-types (Yes/No, Y/N, 0/1, etc).

    And of course you can define them inconsistently, as with any operator. It is your responsibility to return something sensible. The compiler goes no further than requiring neither or both.

    0 讨论(0)
  • 2021-02-01 07:24

    Depending on the system, true can be any non-zero value. In others, it can be any positive value.

    Other systems aren't truly boolean, and allow a third state null or nill for the boolean values, which is why you might overload true and false, versus overloading a single bool operator.

    0 讨论(0)
  • 2021-02-01 07:29

    I've seen people overload the true and false overloads in order to do clever things like building expressions in .NET 2.0, before Linq existed.

    Ayende worked out a syntax like this to build NHibernate criteria queries, using his NHQG project:

    return Repository.FindAll(
        (Where.Publisher.Name == name) &&
        (Where.Publisher.City == city));
    
    0 讨论(0)
提交回复
热议问题