come convertire una stringa in un bool


Risposte:


172

Abbastanza semplice davvero:

bool b = str == "1";

Grazie! Non riesco a credere quanto stavo pensando a questo
grizzasd

79

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!");
        }
    }
}

1
Comportamento di Convert.ToBoolean mostrato in stackoverflow.com/questions/7031964/...
Michael Freidgeim

1
Sentire Boolean.TryParse è preferibile quando un sacco di valori devono essere convertiti in quanto non genera FormatExceptioncome Convert.ToBoolean .
user3613932

47

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!

Necessario per uno script Powershell che legge alcuni dati XML e questo è perfetto!
Alternatex

20
bool b = str.Equals("1")? true : false;

O ancora meglio, come suggerito in un commento qui sotto:

bool b = str.Equals("1");

39
Considero qualsiasi cosa della forma x ? true : falsedivertente.
Kendall Frey

5
bool b = str.Equals("1") Funziona bene e più intuitivo a prima vista.
Erik Philips

@ErikPhilips Non così intuitivo quando la tua stringa strè Null e vuoi che Null venga risolto come False.
MikeTeeVee

7

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));
    }

5

Ho usato il codice seguente per convertire una stringa in booleano.

Convert.ToBoolean(Convert.ToInt32(myString));

Non è necessario chiamare Convert.ToInt32 se le uniche due possibilità sono "1" e "0". Se vuoi considerare altri casi, var isTrue = Convert.ToBoolean ("true") == true && Convert.ToBoolean ("1"); // Sono entrambi veri.
TamusJRoyce

Guarda Mohammad Sepahv e rispondi al commento di Michael Freidgeim!
TamusJRoyce

3

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;
    }
}

3
    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));
}

1

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");
        }

0

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

-1

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'

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.