Changing bool values to opposite of the initial value

后端 未结 7 702
天命终不由人
天命终不由人 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: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.

提交回复
热议问题