Mam stringwartość „0” lub „1” i jest gwarantowane, że nie będzie to nic innego.
Powstaje więc pytanie: jaki jest najlepszy, najprostszy i najbardziej elegancki sposób przekształcenia tego w plik bool?
Mam stringwartość „0” lub „1” i jest gwarantowane, że nie będzie to nic innego.
Powstaje więc pytanie: jaki jest najlepszy, najprostszy i najbardziej elegancki sposób przekształcenia tego w plik bool?
Odpowiedzi:
Rzeczywiście całkiem proste:
bool b = str == "1";
Ignorując specyficzne potrzeby tego pytania i choć rzutowanie ciągu na bool nigdy nie jest dobrym pomysłem, jednym ze sposobów byłoby użycie metody ToBoolean () w klasie Convert:
bool val = Convert.ToBoolean("true");
lub metoda rozszerzenia, aby wykonać dowolne dziwne mapowanie, które robisz:
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!");
}
}
}
FormatExceptionjak Convert.ToBoolean .
Wiem, że to nie odpowiada na twoje pytanie, ale tylko po to, aby pomóc innym ludziom. Jeśli próbujesz przekonwertować ciągi „prawda” lub „fałsz” na wartości logiczne:
Spróbuj 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;
Lub nawet lepiej, jak zasugerowano w komentarzu poniżej:
bool b = str.Equals("1");
x ? true : falsezabawne.
bool b = str.Equals("1") Na pierwszy rzut oka działa dobrze i jest bardziej intuicyjny.
strma wartość Null i chcesz, aby wartość Null była rozpoznawana jako fałsz.
Stworzyłem coś bardziej rozszerzalnego, łącząc się z koncepcją Mohammada Sepahvanda:
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));
}
Użyłem poniższego kodu, aby przekonwertować ciąg znaków na wartość logiczną.
Convert.ToBoolean(Convert.ToInt32(myString));
Oto moja próba uzyskania najbardziej wyrozumiałej konwersji ciągu znaków na bool, która jest nadal przydatna, w zasadzie wyłączając tylko pierwszy znak.
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));
}
Używam tego:
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");
}
Uwielbiam metody rozszerzeń i to jest ta, której używam ...
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;
}
}
Następnie, aby go użyć, po prostu zrób coś takiego ...
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
Jeśli chcesz sprawdzić, czy ciąg jest prawidłową wartością logiczną bez żadnych wyjątków, możesz spróbować tego:
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");
}
dane wyjściowe is Boolean
i dane wyjściowe dla stringToBool2 to: 'is not Boolean'