【问题标题】:how to convert a string to a bool如何将字符串转换为布尔值
【发布时间】:2012-04-02 07:38:20
【问题描述】:

我有一个string,它可以是“0”或“1”,并且保证不会是其他任何东西。

所以问题是:将其转换为bool 的最佳、最简单和最优雅的方法是什么?

【问题讨论】:

标签: c# type-conversion


【解决方案1】:

确实很简单:

bool b = str == "1";

【讨论】:

  • 谢谢!我不敢相信我想了这么多
【解决方案2】:

忽略此问题的特定需求,虽然将字符串转换为布尔值绝不是一个好主意,但一种方法是在 Convert 类上使用 ToBoolean() 方法:

bool val = Convert.ToBoolean("true");

或扩展方法来做任何奇怪的映射:

public static class StringExtensions
{
    public static bool ToBoolean(this string value)
    {
        switch (value.ToLower())
        {
            case  "true":
                return true;
            case "t":
                return true;
            case "1":
                return true;
            case "0":
                return false;
            case "false":
                return false;
            case "f":
                return false;
            default:
                throw new InvalidCastException("You can't cast that value to a bool!");
        }
    }
}

【讨论】:

【解决方案3】:

我知道这并不能回答您的问题,而只是为了帮助其他人。如果您尝试将“true”或“false”字符串转换为布尔值:

试试 Boolean.Parse

bool val = Boolean.Parse("true"); ==> true
bool val = Boolean.Parse("True"); ==> true
bool val = Boolean.Parse("TRUE"); ==> true
bool val = Boolean.Parse("False"); ==> false
bool val = Boolean.Parse("1"); ==> Exception!
bool val = Boolean.Parse("diffstring"); ==> Exception!

【讨论】:

  • Powershell 脚本需要它来读取一些 XML 数据,这是完美的!
【解决方案4】:
bool b = str.Equals("1")? true : false;

或者甚至更好,如下面的评论中所建议的:

bool b = str.Equals("1");

【讨论】:

  • 我认为任何形式的 x ? true : false 幽默。
  • bool b = str.Equals("1") 工作正常,乍一看更直观。
  • @ErikPhilips 当您的字符串 str 为 Null 并且您希望 Null 解析为 False 时,这不是很直观。
【解决方案5】:

我做了一些更可扩展的东西,捎带 Mohammad Sepahvand 的概念:

    public static bool ToBoolean(this string s)
    {
        string[] trueStrings = { "1", "y" , "yes" , "true" };
        string[] falseStrings = { "0", "n", "no", "false" };


        if (trueStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return true;
        if (falseStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return false;

        throw new InvalidCastException("only the following are supported for converting strings to boolean: " 
            + string.Join(",", trueStrings)
            + " and "
            + string.Join(",", falseStrings));
    }

【讨论】:

    【解决方案6】:

    我使用下面的代码将字符串转换为布尔值。

    Convert.ToBoolean(Convert.ToInt32(myString));
    

    【讨论】:

    • 如果只有“1”和“0”两种可能性,则无需调用 Convert.ToInt32。如果您想考虑其他情况, var isTrue = Convert.ToBoolean("true") == true && Convert.ToBoolean("1"); // 都是真的。
    • 看看 Mohammad Sepahvand 回答 Michael Freidgeim 的评论!
    【解决方案7】:

    这是我尝试的最宽容的字符串到布尔转换,它仍然有用,基本上只关闭第一个字符。

    public static class StringHelpers
    {
        /// <summary>
        /// Convert string to boolean, in a forgiving way.
        /// </summary>
        /// <param name="stringVal">String that should either be "True", "False", "Yes", "No", "T", "F", "Y", "N", "1", "0"</param>
        /// <returns>If the trimmed string is any of the legal values that can be construed as "true", it returns true; False otherwise;</returns>
        public static bool ToBoolFuzzy(this string stringVal)
        {
            string normalizedString = (stringVal?.Trim() ?? "false").ToLowerInvariant();
            bool result = (normalizedString.StartsWith("y") 
                || normalizedString.StartsWith("t")
                || normalizedString.StartsWith("1"));
            return result;
        }
    }
    

    【讨论】:

      【解决方案8】:
          private static readonly ICollection<string> PositiveList = new Collection<string> { "Y", "Yes", "T", "True", "1", "OK" };
      
      public static bool ToBoolean(this string input)
      {
                      return input != null && PositiveList.Any(λ => λ.Equals(input, StringComparison.OrdinalIgnoreCase));
      }
      

      【讨论】:

        【解决方案9】:

        我用这个:

        public static bool ToBoolean(this string input)
                {
                    //Account for a string that does not need to be processed
                    if (string.IsNullOrEmpty(input))
                        return false;
        
                    return (input.Trim().ToLower() == "true") || (input.Trim() == "1");
                }
        

        【讨论】:

          【解决方案10】:

          我喜欢扩展方法,这是我使用的方法...

          static class StringHelpers
          {
              public static bool ToBoolean(this String input, out bool output)
              {
                  //Set the default return value
                  output = false;
          
                  //Account for a string that does not need to be processed
                  if (input == null || input.Length < 1)
                      return false;
          
                  if ((input.Trim().ToLower() == "true") || (input.Trim() == "1"))
                      output = true;
                  else if ((input.Trim().ToLower() == "false") || (input.Trim() == "0"))
                      output = false;
                  else
                      return false;
          
                  //Return success
                  return true;
              }
          }
          

          然后要使用它,只需执行类似...

          bool b;
          bool myValue;
          data = "1";
          if (!data.ToBoolean(out b))
            throw new InvalidCastException("Could not cast to bool value from data '" + data + "'.");
          else
            myValue = b;  //myValue is True
          

          【讨论】:

            【解决方案11】:
            string sample = "";
            
            bool myBool = Convert.ToBoolean(sample);
            

            【讨论】:

              【解决方案12】:

              如果你想测试一个字符串是否是一个没有任何抛出异常的有效布尔值,你可以试试这个:

                  string stringToBool1 = "true";
                  string stringToBool2 = "1";
                  bool value1;
                  if(bool.TryParse(stringToBool1, out value1))
                  {
                      MessageBox.Show(stringToBool1 + " is Boolean");
                  }
                  else
                  {
                      MessageBox.Show(stringToBool1 + " is not Boolean");
                  }
              

              输出is Boolean stringToBool2 的输出是:'is not Boolean'

              【讨论】:

                猜你喜欢
                • 2011-02-17
                • 2021-02-23
                • 1970-01-01
                • 2018-09-07
                • 1970-01-01
                • 2016-07-13
                • 2011-11-12
                • 2012-03-10
                相关资源
                最近更新 更多