Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

c# - How does operator overloading of true and false work?

You can overload operator true and false i looked at examples and found this http://msdn.microsoft.com/en-us/library/aa691312%28v=vs.71%29.aspx

I completely dont understand how they work. I know if i write if(obj) and true returns true then the if is executed. It doesnt matter what false returns. However how does false work? in that doc it is suggected that the && operator uses it. I wrote the code below. I dont know how to get && to compile. || gives me a compile error too. How do i get false to be called? and how do i get the && and || to work?

        var ts= new MyTimeSpan();// ts += ts;
        if (ts){ Console.WriteLine("Is true"); }
        else { Console.WriteLine("not true"); }
        //Console.WriteLine(ts && ts ? "Y" : "N");

    class MyTimeSpan
    {
        public static MyTimeSpan operator +(MyTimeSpan t, MyTimeSpan t2) { return new MyTimeSpan(); }
        public static bool operator true(MyTimeSpan t) { return true; }
        public static bool operator false(MyTimeSpan t) { return false; }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The defining property of a short circuiting operator is that it doesn't need to evaluate the right side if the left side already determines the result. For or if the left side is true the result will be true in any case and it's unnecessary to evaluate the right side. For and it's the same except that if the left side is false the result will be false.

You need to overload both | and true to get ||. And & and false to get &&.

a||b corresponds to something like op_true(a)?a:(a|b). So if the true operator returns true it does not need to evaluate the expression of b.

a&&b corresponds to something like op_false(a)?a:(a&b). So if the false operator returns true it does not need to evaluate the expression of b.

Overloading the short circuiting operators is useful when creating a custom boolean type, such as nullable bools(See DBBool)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...