Convert.ToBoolean fails with “0” value

后端 未结 8 2225
清歌不尽
清歌不尽 2020-12-14 16:37

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

var myValue = Convert.To         


        
相关标签:
8条回答
  • 2020-12-14 17:20

    If you know that it would be an int then you can convert it to int then to bool. Following will try for conversion to bool by attempting the string then attempting with number.

    public bool ToBoolean(string value)
    {
      var boolValue = false;
      if (bool.TryParse(value, out boolValue ))
      {
        return boolValue;
      }
    
      var number = 0;
      int.TryParse(value, out number))
      return Convert.ToBoolean(number);
    }
    
    0 讨论(0)
  • 2020-12-14 17:29

    Since it's really a matter of still doing those conversions and such, how about an extension method?

    public static class Extensions {
        public static bool ToBool(this string s) {
            return s == "0" ? false : true;
        }
    }
    

    and so then you would use it like this:

    "0".ToBool();
    

    and now you could easily extend this method to handle even more cases if you wanted.

    0 讨论(0)
  • 2020-12-14 17:29

    For a successful conversion to occur, the value parameter must equal either Boolean.TrueString, a constant whose value is True, Boolean.FalseString, a constant whose value is False, or it must be null. In comparing value with Boolean.TrueString and Boolean.FalseString, the method ignores case as well as leading and trailing white space.

    from MSDN

    because Convert.ToBoolean expects a true if value is not zero; otherwise, false. numerical value and True or False String value.

    0 讨论(0)
  • 2020-12-14 17:31
        public static bool GetBoolValue(string featureKeyValue)
        {
            if (!string.IsNullOrEmpty(featureKeyValue))
            {
                        try 
                        {
                            bool value;
                            if (bool.TryParse(featureKeyValue, out value))
                            {
                                return value;
                            }
                            else
                            {
                                return Convert.ToBoolean(Convert.ToInt32(featureKeyValue));
                            }
                        }
                        catch
                        {
                            return false;
                        }
             }
             else
             {
                      return false;
             }
       }
    

    You can call it like following -:

    GetBoolValue("TRUE") // true
    GetBoolValue("1") // true
    GetBoolValue("") // false
    GetBoolValue(null) // false
    GetBoolValue("randomString") // false
    
    0 讨论(0)
  • 2020-12-14 17:37

    Fast enough and simple:

    public static class Extensions
    {
            static private List<string> trueSet = new List<string> { "true","1","yes","y" };
    
            public static Boolean ToBoolean(this string str)
            {
                try
                { return trueSet.Contains(str.ToLower()); }
                catch { return false; }
            }
    }
    
    0 讨论(0)
  • 2020-12-14 17:39

    Here's a very forgiving parser that keys off of the first character:

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题