如何将字符串转换为布尔型

91

我有一个字符串 string,它只能是 "0" 或 "1",保证不会出现其他情况。

问题是:如何将其转换为 bool 类型,要求方法最好、最简单、最优雅?


3
如果输入可能包含意外的值,请考虑使用TryParse方法(https://dev59.com/FmMl5IYBdhLWcg3wiXZ7#18329085)。 - Michael Freidgeim
12个回答

184

非常简单:

bool b = str == "1";

2
谢谢!我简直不敢相信我过度思考了这么多。 - grizzasd

85
忽略此问题的具体需求,虽然将字符串转换为布尔值并不是一个好主意,但一种方法是使用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
Convert.ToBoolean的行为在https://dev59.com/cGw05IYBdhLWcg3wykvn#26202581中有所展示。 - Michael Freidgeim
2
当需要转换大量值时,建议使用Boolean.TryParse,因为它不会像Convert.ToBoolean一样抛出FormatException异常。 - user3613932

51

我知道这并不回答你的问题,但可以帮助其他人。如果你想把 "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");

40
我认为任何形式为 x ? true : false 的东西都有些滑稽。 - Kendall Frey
5
bool b = str.Equals("1") 看起来很直观并且可以正常工作。 - Erik Philips
1
@ErikPhilips 当你的字符串str为空时,想让Null解析为False并不那么直观。 - MikeTeeVee

8

我做了一些更加可扩展的东西,借鉴了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));
    }

5
我使用以下代码将字符串转换为布尔值。
Convert.ToBoolean(Convert.ToInt32(myString));

如果只有“1”和“0”两种可能性,那么调用Convert.ToInt32是不必要的。如果您想考虑其他情况,可以使用以下代码:var isTrue = Convert.ToBoolean("true") == true && Convert.ToBoolean("1"); // 两者都为真。 - TamusJRoyce
看看Mohammad Sepahvand回复Michael Freidgeim的评论! - TamusJRoyce

3
这是一个关于将字符串转换为布尔值的最宽容的尝试,仍然有用,基本上只依赖于第一个字符。
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接