Ho un stringche può essere "0" o "1" ed è garantito che non sarà nient'altro.
Quindi la domanda è: qual è il modo migliore, più semplice ed elegante per convertirlo in un bool?
Ho un stringche può essere "0" o "1" ed è garantito che non sarà nient'altro.
Quindi la domanda è: qual è il modo migliore, più semplice ed elegante per convertirlo in un bool?
Risposte:
Abbastanza semplice davvero:
bool b = str == "1";
Ignorando le esigenze specifiche di questa domanda e sebbene non sia mai una buona idea eseguire il cast di una stringa in un bool, un modo sarebbe usare il metodo ToBoolean () sulla classe Convert:
bool val = Convert.ToBoolean("true");
o un metodo di estensione per eseguire qualsiasi mappatura strana che stai facendo:
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!");
}
}
}
FormatExceptioncome Convert.ToBoolean .
So che questo non risponde alla tua domanda, ma solo per aiutare altre persone. Se stai tentando di convertire stringhe "vere" o "false" in booleane:
Prova 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;
O ancora meglio, come suggerito in un commento qui sotto:
bool b = str.Equals("1");
x ? true : falsedivertente.
bool b = str.Equals("1") Funziona bene e più intuitivo a prima vista.
strè Null e vuoi che Null venga risolto come False.
Ho creato qualcosa di un po 'più estensibile, basandomi sul concetto di 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));
}
Ho usato il codice seguente per convertire una stringa in booleano.
Convert.ToBoolean(Convert.ToInt32(myString));
Ecco il mio tentativo di convertire la stringa più indulgente in bool che è ancora utile, fondamentalmente chiudendo solo il primo carattere.
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));
}
Io uso questo:
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");
}
Adoro i metodi di estensione e questo è quello che 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;
}
}
Quindi per usarlo basta fare qualcosa come ...
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 vuoi verificare se una stringa è un booleano valido senza eccezioni generate, puoi provare questo:
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");
}
output is Boolean
e l'output per stringToBool2 è: 'non è booleano'