C# 解析为布尔值或检查字符串值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18329001/
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
Parse to Boolean or check String Value
提问by TheGeekZn
If I have a variable that pulls a string of true
or false
from the DB,
which would be the preferred way of checking its value?
如果我有一个变量可以从数据库中提取字符串true
或false
从数据库中提取字符串,那么
哪种方法是检查其值的首选方法?
string value = "false";
if(Boolean.Parse(value)){
DoStuff();
}
I know there are different ways of parsing to bool - this is an example
or
我知道有多种解析 bool 的方法 - 这是一个例子
或
string value = "false";
if(value == "true"){
DoStuff();
}
I am pulling a lot of true/false values from the DB in string
format, and want to know if these methods make any performance difference at all?
我从数据库中提取了很多string
格式的真/假值,想知道这些方法是否有任何性能差异?
采纳答案by ProgramFOX
Use Boolean.TryParse
:
string value = "false";
Boolean parsedValue;
if (Boolean.TryParse(value, out parsedValue))
{
if (parsedValue)
{
// do stuff
}
else
{
// do other stuff
}
}
else
{
// unable to parse
}
回答by Adriaan Stander
The only issue I can see here is that C# does case sensitive comparisons, so if the database value was "True"
我在这里看到的唯一问题是 C# 进行区分大小写的比较,因此如果数据库值为“True”
(value == "true")
would return false.
会返回假。
But looking at the example Boolean.Parse Method
但是看示例Boolean.Parse Method
string[] values = { null, String.Empty, "True", "False",
"true", "false", " true ", "0",
"1", "-1", "string" };
foreach (var value in values) {
try {
bool flag = Boolean.Parse(value);
Console.WriteLine("'{0}' --> {1}", value, flag);
}
catch (ArgumentException) {
Console.WriteLine("Cannot parse a null string.");
}
catch (FormatException) {
Console.WriteLine("Cannot parse '{0}'.", value);
}
}
// The example displays the following output:
// Cannot parse a null string.
// Cannot parse ''.
// 'True' --> True
// 'False' --> False
// 'true' --> True
// 'false' --> False
// ' true ' --> True
// Cannot parse '0'.
// Cannot parse '1'.
// Cannot parse '-1'.
// Cannot parse 'string'.
Bool.Parse seems a little bit more robust.
Bool.Parse 似乎更健壮一点。
回答by Sam Leach
If you know the string will be a valid "true"
or "false"
string your first method is prefered.
如果您知道字符串将是有效的"true"
或"false"
字符串,则首选您的第一种方法。
Otherwise, you could use Boolean.TryParse
否则,你可以使用 Boolean.TryParse
回答by Ant P
I would always parse it - your application should be robust against invalid values (even if you "know" your database will always be valid):
我总是会解析它 - 您的应用程序应该对无效值具有健壮性(即使您“知道”您的数据库将始终有效):
bool myVal;
if (!Boolean.TryParse(value, out myVal))
{
throw new InvalidCastException(...); // Or do something else
}
回答by Tobia Zambon
For sure use Boolean.TryParse()
, you will avoid case-sensitive issues that can pop up.
确保使用Boolean.TryParse()
,您将避免可能弹出的区分大小写的问题。
回答by LunicLynx
When asking for performance the version without parsing will probably be the faster one. But as others already suggested i also would prefer the parsing solution.
当要求性能时,没有解析的版本可能会更快。但正如其他人已经建议的那样,我也更喜欢解析解决方案。
回答by Anderson Costa
string value = "your text"
bool outresult = false;
bool resultado = false;
resultado = bool.TryParse(value, out outresult);
The try parse function will try to convert the value of the string to boolean, if it can not return the value of the variable outresult.
如果无法返回变量outresult 的值,try parse 函数将尝试将字符串的值转换为布尔值。