Convert.ToBoolean fails with “0” value

2020-02-08 15:30发布

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

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

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.

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"));
  • 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?

8条回答
我想做一个坏孩纸
2楼-- · 2020-02-08 15:49
    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
查看更多
迷人小祖宗
3楼-- · 2020-02-08 15:53

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;
    }
}
查看更多
▲ chillily
4楼-- · 2020-02-08 15:54

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; }
        }
}
查看更多
SAY GOODBYE
5楼-- · 2020-02-08 16:01

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.

查看更多
Animai°情兽
6楼-- · 2020-02-08 16:02

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.

查看更多
We Are One
7楼-- · 2020-02-08 16:04
public static class BooleanParser
{
    public static bool SafeParse(string value)
    {
        var s = (value ?? "").Trim().ToLower();
        return s == "true" || s == "1";
    }
}

static readonly HashSet<string> _booleanTrueStrings = new HashSet<string> { "true", "yes", "1" };
static readonly HashSet<string> _booleanFalseStrings = new HashSet<string> { "false", "no", "0" };

public static bool ToBoolean(string value)
{
    var v = value?.ToLower()?.Trim() ?? "";
    if (_booleanTrueStrings.Contains(v)) return true;
    if (_booleanFalseStrings.Contains(v)) return false;
    throw new ArgumentException("Unexpected Boolean Format");
}
查看更多
登录 后发表回答