2012-03-16 97 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)); 
} 
相關問題