eu tenho um string que pode ser "0" ou "1" e é garantido que não será qualquer outra coisa.
Portanto, a questão é: qual é a maneira melhor, mais simples e mais elegante de converter isso em um bool?
eu tenho um string que pode ser "0" ou "1" e é garantido que não será qualquer outra coisa.
Portanto, a questão é: qual é a maneira melhor, mais simples e mais elegante de converter isso em um bool?
Respostas:
Muito simples:
bool b = str == "1";
Ignorando as necessidades específicas desta questão, e embora nunca seja uma boa ideia converter uma string para um bool, uma maneira seria usar o método ToBoolean () na classe Convert:
bool val = Convert.ToBoolean("true");
ou um método de extensão para fazer qualquer mapeamento estranho que você esteja fazendo:
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!");
}
}
}
FormatExceptioncomo Convert.ToBoolean .
Eu sei que isso não responde a sua pergunta, mas apenas para ajudar outras pessoas. Se você estiver tentando converter strings "verdadeiras" ou "falsas" em booleanas:
Experimente 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;
Ou melhor ainda, como sugerido em um comentário abaixo:
bool b = str.Equals("1");
x ? true : falseengraçada.
bool b = str.Equals("1") Funciona bem e de forma mais intuitiva à primeira vista.
stré Null e você deseja que Null resolva como False.
Eu fiz algo um pouco mais extensível, pegando carona no conceito de 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));
}
Usei o código abaixo para converter uma string em booleano.
Convert.ToBoolean(Convert.ToInt32(myString));
Aqui está minha tentativa de conversão de string em bool mais tolerante que ainda é útil, basicamente desligando apenas o primeiro caractere.
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;
}
}
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));
}
Eu uso isso:
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");
}
Eu amo métodos de extensão e este é o que eu uso ...
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;
}
}
Então, para usá-lo, faça algo como ...
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
Se você quiser testar se uma string é um booleano válido sem nenhuma exceção lançada, você pode tentar isto:
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");
}
saída is Boolean
e a saída para stringToBool2 é: 'não é Boolean'