C# 我可以“反转”一个布尔值吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8912353/
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
Can I 'invert' a bool?
提问by Simon Verbeke
I have some checks to see if a screen is active. The code looks like this:
我有一些检查以查看屏幕是否处于活动状态。代码如下所示:
if (GUI.Button(new Rect(Screen.width / 2 - 10, 50, 50, 30), "Rules")) //Creates a button
{
if (ruleScreenActive == true) //check if the screen is already active
ruleScreenActive = false; //handle according to that
else
ruleScreenActive = true;
}
Is there any way to - whenever I click the button - invert the value of ruleScreenActive?
有什么方法可以 - 每当我单击按钮时 - 反转 的值ruleScreenActive?
(This is C# in Unity3D)
(这是 Unity3D 中的 C#)
采纳答案by Ahmad Mageed
You can get rid of your if/else statements by negating the bool's value:
您可以通过否定 bool 的值来摆脱 if/else 语句:
ruleScreenActive = !ruleScreenActive;
回答by MusiGenesis
ruleScreenActive = !ruleScreenActive;
回答by Hyman
I think it is better to write:
我认为最好这样写:
ruleScreenActive ^= true;
that way you avoid writing the variable name twice ... which can lead to errors
这样你就可以避免两次写变量名......这可能会导致错误
回答by Hyman
This would be inlined, so readability increases, runtime costs stays the same:
这将被内联,因此可读性增加,运行时成本保持不变:
public static bool Invert(this bool val) { return !val; }
To give:
给予:
ruleScreenActive.Invert();

