C# 将 bool 值更改为与初始值相反的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18018289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:04:00  来源:igfitidea点击:

Changing bool values to opposite of the initial value

c#c++cboolean

提问by user1046403

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

这对你来说可能听起来很奇怪,但我懒得每次都写

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

isn't there is something like int++ or int-- to change bool value to opposite of its value?

是不是有像 int++ 或 int-- 之类的东西可以将 bool 值更改为与其值相反的值?

回答by p.s.w.g

Just do this:

只需这样做:

threadAlive = !threadAlive;

回答by piokuc

Very simple:

很简单:

threadAlive = ! threadAlive;

回答by Habib

This would do it:

这样做:

threadAlive = !threadAlive;

The correct term is Toggle

正确的术语是切换

回答by ouah

Use the !operator:

使用!运算符:

bool b = true;

b = !b;   // b is now false

回答by Kyle_the_hacker

The logical negation operator !is a unary operator that negates its operand. It is defined for booland returns trueif and only if its operand is falseand falseif and only if its operand is true:

逻辑否定运算符!是一个否定其操作数的一元运算符。当且仅当其操作数为且当且仅当其操作数为 时,它被定义bool并返回:truefalsefalsetrue

threadAlive = !threadAlive;

回答by xanatos

Yes, there is!

就在这里!

threadAlive ^= true;

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

(这是一个 C# 笑话,在最一般的情况下它不会在 C/C++/Javascript 中工作(它可以在 C/C++/Javascript 中工作,具体取决于某些条件),但这是真的!^是异或运算符)

回答by Avram Tudor

You can't overload operatorsfor 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 booltype and overload the ++or whatever operator you wish to invert your value.

但是,虽然我永远不会推荐,但您可以创建自己的bool类型并重载++或您希望反转值的任何运算符。

The following code is something that should neverbe 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.

您也可以创建自己的扩展方法,但这也不是更好的方法。