如何将字符串转换为布尔


Answers:



79

忽略此问题的具体需求,尽管将字符串转换为布尔值从来不是一个好主意,但一种方法是在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!");
        }
    }
}


1
感觉Boolean.TryParse最好的时候需要大量的值转换,因为它不会引发FormatExceptionConvert.ToBoolean
user3613932

47

我知道这不会回答您的问题,而只是为了帮助其他人。如果您尝试将“ 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数据,这是完美的!
Alternatex

20
bool b = str.Equals("1")? true : false;

甚至更好,如以下评论中所建议:

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

39
我认为任何形式的x ? true : false幽默。
肯德尔·弗雷

5
bool b = str.Equals("1") 乍一看效果很好,更直观。
Erik Philips

@ErikPhilips当您的Stringstr为Null并且您希望Null解析为False时,不是那么直观。
MikeTeeVee

7

我在Mohammad Sepahvand的概念上Pi带了一些可扩展的内容:

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

5

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

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

如果只有两个可能是“ 1”和“ 0”,则不必调用Convert.ToInt32。如果要考虑其他情况,则var isTrue = Convert.ToBoolean(“ true”)== true && Convert.ToBoolean(“ 1”); //都是正确的。
TamusJRoyce '02

看看Mohammad Sepahvand回答Michael Freidgeim的评论!
TamusJRoyce'2

3

这是我尝试的最宽容的字符串到bool转换,它仍然很有用,基本上仅键入第一个字符。

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

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

1

我用这个:

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

0

我喜欢扩展方法,这是我使用的一种方法。

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

-1

如果要测试字符串是否为有效的布尔值且没有引发任何异常,则可以尝试以下操作:

    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的输出为:“不是布尔值”

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.