.net Convert.ToBoolean 和 Boolean.Parse 不接受 0 和 1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1903776/
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
Convert.ToBoolean and Boolean.Parse don't accept 0 and 1
提问by Brett Allen
Why was it decided that when parsing a boolean, 0/1 are not acceptable?
为什么决定在解析布尔值时,0/1 是不可接受的?
When parsing any integer type value, it accepts numerical strings to be parsed. (And if .NET can parse the string "One hundred million two hundred and sixty five thousand eight hundred and sixty five" I would be surprised).
在解析任何整数类型值时,它接受要解析的数字字符串。(如果 .NET 可以解析字符串“一亿二十六万五千八百六十五”,我会感到惊讶)。
What makes booleans special? They are essentially 0 as false, and non-zero as true in my experience...
是什么让布尔值特别?根据我的经验,它们基本上是 0 为假,非零为真......
Is there a bcl method to parse a string like this, and if not, why?
是否有 bcl 方法来解析这样的字符串,如果没有,为什么?
Note: I forgot to specify in a string "0" and "1". Curious though that if already an int it works as I anticipated. Maybe this caused the confusion.
注意:我忘记在字符串中指定“0”和“1”。好奇的是,如果已经是 int ,它会按我的预期工作。也许这引起了混乱。
回答by Aric TenEyck
0 and (not-zero) are not equal to "false" and "true", they're just the representation chosen by C. Other languages use 0 for true and -1 for false, or other schemes entirely. A boolean is nota 0 or a 1, it's a true or a false.
0 和(非零)不等于“假”和“真”,它们只是 C 选择的表示形式。其他语言使用 0 表示真,-1 表示假,或者完全使用其他方案。布尔值不是0 或 1,而是真或假。
Should it also handle "yes" and "no", "off" and "on", and all of the myriad other things that are analogous to booleans? Where would you draw the line?
它还应该处理“yes”和“no”、“off”和“on”以及所有与布尔值类似的无数其他事物吗?你会在哪里划线?
回答by Anon.
What makes booleans special? They are essentially 0 as false, and non-zero as true in my experience...
是什么让布尔值特别?根据我的经验,它们基本上是 0 为假,非零为真......
That is an implementation detail, and isn't at all relevant.
这是一个实现细节,根本不相关。
trueis a boolean value. falseis a boolean value. Anything else is not.
true是一个布尔值。false是一个布尔值。别的都不是。
If you want to parse something such that the string "0" evaluates falsewhile anything else evaluates true, you can use:
如果你想解析一些东西,使得字符串 "0" 评估false而其他任何东西评估true,你可以使用:
!mystr.Equals("0");
回答by Visual Micro
The shared FormatHelperclass shown below provides a simple solution using two variations of an overloaded method called StringToBoolean.
FormatHelper下面显示的共享类使用称为 的重载方法的两种变体提供了一个简单的解决方案StringToBoolean。
FormatHelper.StringToBoolean(String value)
FormatHelper.StringToBoolean(String value, Boolean NullOrEmptyDefault)
Both variations provide a case-insentive string match
两种变体都提供区分大小写的字符串匹配
1) The normal convertion from string to boolean defaulting empty or null strings to false
1) 从字符串到布尔值的正常转换默认为空或空字符串 false
The following examples will result in a booleanvalue of false:-
以下示例将导致boolean值false:-
Boolean myBool = FormatHelper.StringToBoolean("");
Boolean myBool = FormatHelper.StringToBoolean("0");
Boolean myBool = FormatHelper.StringToBoolean("false");
Boolean myBool = FormatHelper.StringToBoolean("False");
Boolean myBool = FormatHelper.StringToBoolean("no");
Boolean myBool = FormatHelper.StringToBoolean("off");
All other string values will result in a Booleanvalue of truesuch as:-
所有其他字符串值将产生如下Boolean值true:-
Boolean myBool = FormatHelper.StringToBoolean("1");
Boolean myBool = FormatHelper.StringToBoolean("true");
Boolean myBool = FormatHelper.StringToBoolean("True");
Boolean myBool = FormatHelper.StringToBoolean("yes");
Boolean myBool = FormatHelper.StringToBoolean("xyz blah");
Note: Edit the value of BooleanStringOffin the class below to include more (or less) values for false/off
注意:编辑BooleanStringOff下面类中的值以包含更多(或更少)的 false/off 值
2) Follows the same rules as 1) above but allows a default value of trueto be supplied as the 2nd argument to the conversion.
2) 遵循与上述 1) 相同的规则,但允许将 的默认值true作为第二个参数提供给转换。
The default value is used when the Stringvalue is empty or null. This is useful if a missing string value needs to signify a truestate.
当String值为空或时使用默认值null。如果缺少的字符串值需要表示true状态,这将很有用。
The following code example will return true
以下代码示例将返回 true
Boolean myBool = FormatHelper.StringToBoolean("",true);
The following code example will return false
以下代码示例将返回 false
Boolean myBool = FormatHelper.StringToBoolean("false",true);
This is the code for the FormatHelperclass
这是FormatHelper类的代码
public class FormatHelper
{
public static Boolean StringToBoolean(String str)
{
return StringToBoolean(str, false);
}
public static Boolean StringToBoolean(String str, Boolean bDefault)
{
String[] BooleanStringOff = { "0", "off", "no" };
if (String.IsNullOrEmpty(str))
return bDefault;
else if(BooleanStringOff.Contains(str,StringComparer.InvariantCultureIgnoreCase))
return false;
Boolean result;
if (!Boolean.TryParse(str, out result))
result = true;
return result;
}
}
回答by Josh
Unfortunately, this happens a lot in .NET. For example, I can't remember if it's XML Serializer or XmlConvert but one of them fails if the casing of True/False are not correct.
不幸的是,这种情况在 .NET 中经常发生。例如,我不记得它是 XML Serializer 还是 XmlConvert 但如果 True/False 的大小写不正确,其中之一就会失败。
You can round trip through integer to get what you want.
你可以通过整数来回得到你想要的。
string s = "2";
int i = Convert.ToInt32(s);
bool b = Convert.ToBoolean(i);
In the above case, anything non-zero will evaluate to true.
在上述情况下,任何非零值都将评估为真。
For this reason, I created a class I use all over called ConversionStrategy which takes into account the source type and destination type and chooses the most ideal (and flexible) conversion strategy for making the conversion.
出于这个原因,我创建了一个名为 ConversionStrategy 的类,它考虑了源类型和目标类型,并选择最理想(和灵活)的转换策略进行转换。
回答by tobias Tornqvist
How about this?
这个怎么样?
byte i = 1; //or 0
bool myBool = BitConverter.ToBoolean(new byte[] { i }, 0)
回答by Cory Charlton
You want Convert.ToBoolean(int value)not sure what's up with the Parse methods :-)
你想Convert.ToBoolean(int value)不确定 Parse 方法是怎么回事:-)
Code for no useful purpose:
无用的代码:
int falseInt = 0;
int trueInt = 1;
bool falseBool;
bool trueBool;
if (bool.TryParse(falseInt.ToString(), out falseBool))
{
if (!falseBool)
{
MessageBox.Show("TryParse: False");
}
}
if (bool.TryParse(trueInt.ToString(), out trueBool))
{
if (!trueBool)
{
MessageBox.Show("TryParse: True");
}
}
falseBool = Convert.ToBoolean(falseInt);
trueBool = Convert.ToBoolean(trueInt);
if (!falseBool)
{
MessageBox.Show("Convert: False");
}
if (trueBool)
{
MessageBox.Show("Convert: True");
}
回答by Arvo Bowen
To answer the question would be hard. Maybe because the narrow minded developers at Microsoft had their own reasons? No disrespect intended to them. Just saying they did not think about what it would need to be used for or how it would be used. I can't think of a reason why my extension below would not work for anyone. I mean a Boolean value is either on or off, true or false. In my mind it's basically binary. Parse methods for Int, Double, Char, Long, Byte, etc are more forgiving with their Parse methods.
要回答这个问题会很困难。也许是因为微软心胸狭隘的开发者有他们自己的原因?没有对他们不敬的意思。只是说他们没有考虑它需要用来做什么或如何使用。我想不出为什么我下面的扩展对任何人都不起作用。我的意思是布尔值是开或关,真或假。在我看来,它基本上是二进制的。Int、Double、Char、Long、Byte 等的 Parse 方法对它们的 Parse 方法更宽容。
However, consider this; You are looking to see if a value exists in an object. The same might be said for the following...
但是,请考虑这一点;您正在查看对象中是否存在值。对于以下内容,也可能会这样说......
string myvar = "empty"; //Or maybe = "NULL"
if (String.IsNullOrEmpty(myvar))
{
//Should this be true?
}
Anyway, let's just make this simple. Here is my solution using an extension method to create a ToBoolean()method for a string.
不管怎样,让我们把这简单化。这是我使用扩展ToBoolean()方法为字符串创建方法的解决方案。
using System.Linq;
public static bool ToBoolean(this string input)
{
//Define the false keywords
String[] bFalse = { "false", "0", "off", "no" };
//Return false for any of the false keywords or an empty/null value
if (String.IsNullOrEmpty(input) || bFalse.Contains(input.ToLower()))
return false;
//Return true for anything not false
return true;
}

