2012-03-16 98 views
38

我有一个string可以是“0”或“1”,并保证它不会是别的。如何将字符串转换为布尔

所以问题是:什么是最好,最简单和最优雅的方式将其转换为bool

谢谢。

+0

如果有任何意外的值可以在输入,考虑到使用的TryParse(http://stackoverflow.com/questions/18329001/parse-to-boolean-or-check-string-value/ 18329085#18329085) – 2017-01-30 11:33:00

回答

113

很实际很简单:

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

甚至更​​好,如建议在下面留言:

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

我认为形式为'x?真实:假幽默。 – 2012-03-16 18:48:23

+4

'bool b = str.Equals(“1”)'乍一看很好,更直观。 – 2012-03-16 18:52:53

37

忽略这个问题的具体需求,虽然其不是一个好想法将一个字符串投射到布尔,一种方法是在Convert类上使用ToBoolean()方法:

bool boolVal = Convert.ToBoolean("true");

或扩展方法做你正在做什么奇怪的映射:

public static class MyStringExtensions 
{ 
    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 a weird value to a bool!"); 
     } 
    } 
} 
+0

Convert.ToBoolean的行为显示在http://stackoverflow.com/questions/7031964/what-is-the-difference-between-convert-tobooleanstring-and-boolean-parsestrin/26202581#26202581 – 2017-01-30 11:35:37

5

我做的东西一点点扩展,捎带上穆罕默德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)); 
    } 
13

我知道这不会回答你的问题,而只是为了帮助其他人。如果你正试图转换“真”或“假”的字符串为布尔值:

尝试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! 
+0

需要Powershell脚本阅读一些XML数据,这是完美的! – Alternatex 2017-10-12 10:37:13

2

这是我尝试以最宽容的字符串为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; 
    } 
} 
1

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

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

如果只有两种可能性是“1”和“0”,则不必调用Convert.ToInt32。如果你想考虑其他情况,var isTrue = Convert.ToBoolean(“true”)== true && Convert.ToBoolean(“1”); //都是真的。 – TamusJRoyce 2017-02-08 15:06:42

+0

看穆罕默德Sepahvand回答Michael Freidgeim评论! – TamusJRoyce 2017-02-08 15:49:32

0
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)); 
} 
相关问题