Changing bool values to opposite of the initial value

后端 未结 7 699
天命终不由人
天命终不由人 2021-01-03 19:05

This maybe sound strange to you but I\'m too lazy to write everytime like

if (threadAlive)
{
            threadAlive = false;
}
        else
{
            th         


        
相关标签:
7条回答
  • 2021-01-03 19:40

    The logical negation operator ! is a unary operator that negates its operand. It is defined for bool and returns true if and only if its operand is false and false if and only if its operand is true:

    threadAlive = !threadAlive;
    
    0 讨论(0)
  • 2021-01-03 19:48

    Very simple:

    threadAlive = ! threadAlive;
    
    0 讨论(0)
  • 2021-01-03 19:53

    You can't overload operators for basic types if that's what you're looking for.

    As everyone else mentioned already, this is by far your best option:

    threadAlive = !threadAlive;
    

    You can however, although is something I would never recommend, create your own bool type and overload the ++ or whatever operator you wish to invert your value.

    The following code is something that should never be used anyway:

    public class MyBool
    {
        bool Value;
    
        public MyBool(bool value)
        {
            this.Value = value;
        }
    
        public static MyBool operator ++(MyBool myBoolean)
        {
            myBoolean.Value = !myBoolean.Value;
            return myBoolean;
        }
    }
    

    You can also create your own extension method but that won't be be a better way either.

    0 讨论(0)
  • 2021-01-03 19:55

    Yes, there is!

    threadAlive ^= true;
    

    (this is a C# joke, in the most general case it won't work in C/C++/Javascript (it could work in C/C++/Javascript depending on some conditions), but it's true! ^ is the xor operator)

    0 讨论(0)
  • 2021-01-03 19:59

    Just do this:

    threadAlive = !threadAlive;
    
    0 讨论(0)
  • 2021-01-03 20:00

    Use the ! operator:

    bool b = true;
    
    b = !b;   // b is now false
    
    0 讨论(0)
提交回复
热议问题