我有一个string可以是“ 0”或“ 1”的值,并且可以保证它不会是其他任何值。
所以问题是:将其转换为的最佳,最简单和最优雅的方法是bool什么?
我有一个string可以是“ 0”或“ 1”的值,并且可以保证它不会是其他任何值。
所以问题是:将其转换为的最佳,最简单和最优雅的方法是bool什么?
Answers:
忽略此问题的具体需求,尽管将字符串转换为布尔值从来不是一个好主意,但一种方法是在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!");
}
}
}
我知道这不会回答您的问题,而只是为了帮助其他人。如果您尝试将“ 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!
bool b = str.Equals("1")? true : false;
甚至更好,如以下评论中所建议:
bool b = str.Equals("1");
x ? true : false幽默。
bool b = str.Equals("1") 乍一看效果很好,更直观。
str为Null并且您希望Null解析为False时,不是那么直观。
我在Mohammad Sepahvand的概念上Pi带了一些可扩展的内容:
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));
}
我使用以下代码将字符串转换为布尔值。
Convert.ToBoolean(Convert.ToInt32(myString));
这是我尝试的最宽容的字符串到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;
}
}
我喜欢扩展方法,这是我使用的一种方法。
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
如果要测试字符串是否为有效的布尔值且没有引发任何异常,则可以尝试以下操作:
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的输出为:“不是布尔值”