C# 如何将字符串转换为布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9742724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to convert a string to a bool
提问by Sachin Kainth
I have a stringthat can be either "0" or "1", and it is guaranteed that it won't be anything else.
我有一个string可以是“0”或“1”的,并且可以保证它不会是其他任何东西。
So the question is: what's the best, simplest and most elegant way to convert this to a bool?
所以问题是:将它转换为 a 的最佳、最简单和最优雅的方法是bool什么?
采纳答案by Kendall Frey
Quite simple indeed:
确实很简单:
bool b = str == "1";
回答by GETah
bool b = str.Equals("1")? true : false;
Or even better, as suggested in a comment below:
或者甚至更好,如以下评论中所建议:
bool b = str.Equals("1");
回答by Mohammad Sepahvand
Ignoring the specific needs of this question, and while its never a good idea to cast a string to a bool, one way would be to use the ToBoolean()method on the Convert class:
忽略这个问题的特定需求,虽然将字符串转换为 bool 从来都不是一个好主意,但一种方法是在 Convert 类上使用ToBoolean()方法:
bool val = Convert.ToBoolean("true");
bool val = Convert.ToBoolean("true");
or an extension method to do whatever weird mapping you're doing:
或者一个扩展方法来做你正在做的任何奇怪的映射:
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!");
}
}
}
回答by mcfea
I made something a little bit more extensible, Piggybacking on Mohammad Sepahvand's concept:
我做了一些更可扩展的东西,捎带在 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));
}
回答by live-love
I know this doesn't answer your question, but just to help other people. If you are trying to convert "true" or "false" strings to boolean:
我知道这不能回答你的问题,只是为了帮助其他人。如果您尝试将“true”或“false”字符串转换为布尔值:
Try Boolean.Parse
尝试 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!
回答by Mark Meuer
Here's my attempt at the most forgiving string to bool conversion that is still useful, basically keying off only the first character.
这是我尝试最宽容的字符串到布尔转换仍然有用,基本上只关闭第一个字符。
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;
}
}
回答by yogihosting
I used the below code to convert a string to boolean.
我使用以下代码将字符串转换为布尔值。
Convert.ToBoolean(Convert.ToInt32(myString));
回答by Outside the Box Developer
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));
}
回答by Arvo Bowen
I love extension methods and this is the one I use...
我喜欢扩展方法,这是我使用的方法...
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;
}
}
Then to use it just do something like...
然后使用它只是做一些像......
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
回答by Hoang Tran
I use this:
我用这个:
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");
}

