Convert.ToBoolean 以“0"失败;价值

Convert.ToBoolean fails with quot;0quot; value(Convert.ToBoolean 以“0失败;价值)
本文介绍了Convert.ToBoolean 以“0"失败;价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将值 "0" ( System.String ) 转换为其 Boolean 表示形式,例如:

I'm trying to convert the value "0" ( System.String ) to its Boolean representation, like:

var myValue = Convert.ToBoolean("0"); // throwing an exception here

我查看了 MSDN 页面,并在代码示例块中,我找到了这些行:

I've looked at the MSDN page, and in the code-sample block, I found these lines:

ConvertToBoolean("0");
// ...
Unable to convert '0' to a Boolean.

在我的代码中,我将 System.String 转换为 Boolean,如下所示:

In my code, I'm converting from the System.String to Boolean like this:

// will be OK, but ugly code
var myValue = Convert.ToBoolean(Convert.ToInt32("0"));

  • 有没有其他方法可以转换成 Boolean 类型而不用那么难看的代码?
  • 为什么会出现这样的异常?由于从引用类型System.String转换为值类型System.Boolean,但System.Int32也是值类型,不是吗?
    • Is there any other way to convert to the Boolean type with not such ugly code?
    • Why does such an exception occur? Because of converting from the reference type System.String to the value type the System.Boolean, but System.Int32 is also a value type, isn't it?
    • 推荐答案

      发生这种情况是因为 Convert.ToBoolean 期待以下情况之一:

      This is happening because Convert.ToBoolean is expecting one of the following:

      • "True"(字符串)=
      • "False"(字符串)=
      • 0(数值类型;int、double、float 等)= false
      • 任何非0(数字类型;...)= true
      • null = false
      • "True" (String) = true
      • "False" (String) = false
      • 0 (numerical type; int, double, float, etc.) = false
      • Any non-0 (numerical type; ...) = true
      • null = false

      任何 other 值对于 Boolean 都是无效的.

      Any other value is invalid for Boolean.

      已经有了干净的方法:

      var myValue = Convert.ToBoolean(Convert.ToInt32("0"));
      

      <小时>

      您可以创建一个扩展方法来为您处理其中一些情况,同时隐藏处理转换的丑陋.


      You can create an extension method that will handle a few of these cases for you, while hiding away the ugliness of handling the conversion.

      这个扩展提供了一个非常松散的Boolean解释:

      This extension provides a very loose interpretation of Boolean:

      • 真"(字符串)=
      • 假"(字符串)=
      • "0" (String) = false
      • 任何其他字符串 = true
      • "True" (String) = true
      • "False" (String) = false
      • "0" (String) = false
      • Any other string = 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;
          }
      }
      

      虽然不是 cleanpretty 方法,但它保证了获得正确值的更多可能性.而且,Extensions 类隐藏在您的数据/业务代码之外.

      Albeit, not a clean or pretty approach, but it guarantees more possibilities of getting the correct value. And, the Extensions class is tucked away from your data/business code.

      最后,你的转换代码使用起来还是比较简单的:

      In the end, your conversion code is relatively simple to use:

      String myString = "1";
      Boolean myBoolean = myString.ToBoolean();
      

      这篇关于Convert.ToBoolean 以“0"失败;价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)