C# 将 int 转换为布尔值的更好方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15108738/
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
Better way to convert an int to a boolean
提问by DeepSea
The input int
value only consist out of 1 or 0.
I can solve the problem by writing a if else
statement.
输入int
值只包含 1 或 0。我可以通过写一个if else
语句来解决问题。
Isn't there a way to cast the int
into a boolean
?
没有办法将 theint
转换为 aboolean
吗?
采纳答案by Corak
I assume 0
means false
(which is the case in a lot of programming languages). That means true
is not 0
(some languages use -1
some others use 1
; doesn't hurt to be compatible to either). So assuming by "better" you mean less typing, you can just write:
我假设0
意思false
(在很多编程语言中都是这种情况)。这意味着true
是not 0
(有些语言使用-1
一些其他人使用1
;不伤害是兼容两种)。所以假设“更好”意味着更少的打字,你可以这样写:
bool boolValue = intValue != 0;
回答by Evelie
int i = 0;
bool b = Convert.ToBoolean(i);
回答by Rawling
Joking aside, if you're only expecting your input integer to be a zero or a one, you should really be checking that this is the case.
开玩笑,如果您只希望输入的整数是 0 或 1,那么您真的应该检查一下是否是这种情况。
int yourInteger = whatever;
bool yourBool;
switch (yourInteger)
{
case 0: yourBool = false; break;
case 1: yourBool = true; break;
default:
throw new InvalidOperationException("Integer value is not valid");
}
The out-of-the-box Convert
won't check this; nor will yourInteger (==|!=) (0|1)
.
开箱即用的Convert
不会检查这个;也不会yourInteger (==|!=) (0|1)
。