我正在尝试将值 "0"
( System.String
) 转换为其 Boolean
表示形式,例如:
var myValue = Convert.ToBoolean("0"); // throwing an exception here
我看过 MSDN page ,并且在代码示例 block 中,我发现了这些行:
ConvertToBoolean("0");
// ...
Unable to convert '0' to a Boolean.
在我的代码中,我将 System.String
转换为 Boolean
,如下所示:
// will be OK, but ugly code
var myValue = Convert.ToBoolean(Convert.ToInt32("0"));
- 有没有其他方法可以转换为
Boolean
类型而不是这么丑陋的代码? - 为什么会出现这样的异常?因为从引用类型
System.String
转换为值类型System.Boolean
,而System.Int32
也是值类型,不是吗?
最佳答案
这是因为 Convert.ToBoolean
需要以下之一:
-
"True"
(String) =真
-
"False"
(String) =假
0
(数值类型;int、double、float 等)=false
- 任何非
0
(数字类型;...)=true
null
=false
任何 other 值对于 Boolean
都是无效的。
您已经有了一个干净的方法:
var myValue = Convert.ToBoolean(Convert.ToInt32("0"));
编辑:您可以创建一个扩展方法来为您处理其中一些情况,同时隐藏处理转换的丑陋之处。
此扩展提供了对Boolean
的非常松散的解释:
“真”
(字符串)=true
"False"
(字符串)=false
“0”
(字符串)=false
- 任何其他字符串 =
true
代码:
public static class Extensions
{
public static Boolean ToBoolean(this string str)
{
String cleanValue = (str ?? "").Trim();
if (String.Equals(cleanValue, "False", StringComparison.OrdinalIgnoreCase))
return false;
return
(String.Equals(cleanValue, "True", StringComparison.OrdinalIgnoreCase)) ||
(cleanValue != "0");
}
}
或者,如果您想要更严格的方法,它遵循 .NET Framework 的期望;然后简单地使用 try/catch
语句:
public static class Extensions
{
public static Boolean ToBoolean(this string str)
{
try
{
return Convert.ToBoolean(str);
}
catch { }
try
{
return Convert.ToBoolean(Convert.ToInt32(str));
}
catch { }
return false;
}
}
尽管不是干净 或漂亮 方法,但它保证了获得正确值的更多可能性。而且,Extensions
类隐藏在您的数据/业务代码之外。
最后,你的转换代码使用起来还是比较简单的:
String myString = "1";
Boolean myBoolean = myString.ToBoolean();
关于c# - Convert.ToBoolean 失败,值为 "0",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16205436/