Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

c# - Convert.ToBoolean fails with "0" value

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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Any other value is invalid for Boolean.

You've already got a clean approach:

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

Edit: 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.

This extension provides a very loose interpretation of Boolean:

  • "True" (String) = true
  • "False" (String) = false
  • "0" (String) = false
  • Any other string = true

Code:

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");
    }
}

Alternatively, if you want a more strict approach, which follows what the .NET Framework expects; then simply use try/catch statements:

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;
    }
}

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...