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

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

Better way to convert an int to a boolean

c#booleanint

提问by DeepSea

The input intvalue only consist out of 1 or 0. I can solve the problem by writing a if elsestatement.

输入int值只包含 1 或 0。我可以通过写一个if else语句来解决问题。

Isn't there a way to cast the intinto a boolean?

没有办法将 theint转换为 aboolean吗?

采纳答案by Corak

I assume 0means false(which is the case in a lot of programming languages). That means trueis not 0(some languages use -1some 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(在很多编程语言中都是这种情况)。这意味着truenot 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 Convertwon't check this; nor will yourInteger (==|!=) (0|1).

开箱即用的Convert不会检查这个;也不会yourInteger (==|!=) (0|1)