我有string
,可以是“0”或“1”,并保证它不会是其他任何内容。
所以问题是:将此转换为bool
的最佳,最简单和最优雅的方式是什么?
感谢。
答案 0 :(得分:147)
确实很简单:
bool b = str == "1";
答案 1 :(得分:66)
忽略这个问题的特定需求,虽然将字符串强制转换为bool永远不是一个好主意,但一种方法是在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!");
}
}
}
答案 2 :(得分:34)
我知道这并不能回答你的问题,只是为了帮助其他人。如果你想转换" true"或"假"字符串到布尔值:
尝试使用Boolean.Parse
[{"record":
{"ID":"231",
"PARENT_RECORD_ID":"0",
"PARENT_PAGE_ID":"0",
"PARENT_ELEMENT_ID":"0",
"CREATED_DATE":"2015-05-01 10:57:36",
"CREATED_BY":"xxx@gmail.com",
"CREATED_LOCATION":"50.913196:-1.404536:0.000000:0.500000:0.500000:0.000000:0.000000:1430492800.000000",
"CREATED_DEVICE_ID":"207974019024161",
"MODIFIED_DATE":"2015-05-01 10:57:36",
"MODIFIED_BY":"xxx@gmail.com",
"MODIFIED_LOCATION":"50.913196:-1.404536:0.000000:0.500000:0.500000:0.000000:0.000000:1430492800.000000",
"MODIFIED_DEVICE_ID":"207974019024161",
"SERVER_MODIFIED_DATE":"2015-05-01 10:57:43",
"test":"Stack Overflow",
"my_element1":null},
"location":{"type":"point","coordinate":[50.913196,-1.404536]}}]
答案 3 :(得分:19)
bool b = str.Equals("1")? true : false;
甚至更好,正如以下评论所示:
bool b = str.Equals("1");
答案 4 :(得分:6)
我做了一些更具伸缩性的东西,捎带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 :(得分:5)
我使用下面的代码将字符串转换为boolean。
Convert.ToBoolean(Convert.ToInt32(myString));
答案 6 :(得分: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;
}
}
答案 7 :(得分:2)
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));
}
答案 8 :(得分: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
答案 9 :(得分:0)
我用这个:
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");
}
答案 10 :(得分:0)
string sample = "";
bool myBool = Convert.ToBoolean(sample);
答案 11 :(得分:-2)
如果您要测试字符串是否是没有任何抛出异常的有效布尔值,可以尝试以下方法:
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的输出为:“不是布尔值”