如何将string转换为布尔值
我有一个string ,可以是“0”或“1”,并保证它不会是别的。 
 所以问题是:什么是最好,最简单,最优雅的方式来将其转换为bool ? 
谢谢。
确实很简单:
 bool b = str == "1"; 
忽略这个问题的具体需求,虽然它从来不是一个好的想法将一个string转换为布尔值,但一种方法是在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!"); } } } 
 bool b = str.Equals("1")? true : false; 
甚至更好,如下面的评论中所build议的:
 bool b = str.Equals("1"); 
我知道这不能回答你的问题,而只是为了帮助别人。 如果您试图将“true”或“false”string转换为布尔值:
试试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! 
我做了一些更具扩展性的东西,捎带穆罕默德·赛巴万德的概念:
  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)); } 
这里是我最企盼的最宽容的string布尔转换仍然有用,基本上只关键字的第一个字符。
 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; } } 
我用下面的代码将string转换为布尔值。
 Convert.ToBoolean(Convert.ToInt32(myString)); 
  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)); }