bir dizeyi bool'a dönüştürme


Yanıtlar:


175

Gerçekten oldukça basit:

bool b = str == "1";

Teşekkürler! Bunu ne kadar düşündüğüme inanamıyorum
— grizzasd

81

Bu sorunun belirli ihtiyaçlarını göz ardı etmek ve bool'a bir dize atamak asla iyi bir fikir olmasa da, Convert sınıfında ToBoolean () yöntemini kullanmak bir yol olabilir :

bool val = Convert.ToBoolean("true");

veya yaptığınız garip eşlemeyi yapmak için bir uzantı yöntemi:

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
Convert.ToBoolean'ın davranışı stackoverflow.com/questions/7031964/… 'de
— Michael Freidgeim

1
Hisset Boolean. TryParse , Convert.ToBooleanFormatException gibi atılmadığı için çok sayıda değerin dönüştürülmesi gerektiğinde tercih edilir .
— user3613932

49

Bunun sorunuzu yanıtlamadığını biliyorum, sadece diğer insanlara yardım etmek için. "Doğru" veya "yanlış" dizeleri boole'ye dönüştürmeye çalışıyorsanız:

Boolean.Parse'ı deneyin

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!

Bazı XML verilerini okuyan bir Powershell betiği için gerekliydi ve bu mükemmel!
— Alternatex

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

Veya daha da iyisi, aşağıdaki yorumda önerildiği gibi:

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

39
x ? true : falseBiçimdeki her şeyi komik buluyorum.
— Kendall Frey

5
bool b = str.Equals("1") İlk bakışta daha iyi ve sezgisel çalışır.
— Erik Philips

@ErikPhilips String'iniz strNull olduğunda ve Null'un False olarak çözümlenmesini istediğinizde o kadar sezgisel değil .
— MikeTeeVee

8

Mohammad Sepahvand'ın konseptini biraz daha genişletilebilir hale getirdim:

    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

Bir dizeyi boolean'a dönüştürmek için aşağıdaki kodu kullandım.

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

Yalnızca iki olasılık "1" ve "0" ise, Convert.ToInt32'yi çağırmak gereksizdir. Başka durumları değerlendirmek istiyorsanız, var isTrue = Convert.ToBoolean ("true") == true && Convert.ToBoolean ("1"); // İkisi de doğru.
— TamusJRoyce

Mohammad Sepahv'a bakın ve Michael Freidgeim'in yorumuna cevap verin!
— TamusJRoyce

3

İşte, temelde yalnızca ilk karakteri tuşlayarak, hala yararlı olan en bağışlayıcı dizgeden bool dönüşümüne yönelik girişimim.

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

Bunu kullanıyorum:

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

Uzatma yöntemlerini seviyorum ve bu benim kullandığım ...

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

Sonra kullanmak için sadece şöyle bir şey yapın ...

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

Bir dizenin herhangi bir istisna atılmadan geçerli bir Boole olup olmadığını test etmek istiyorsanız, şunu deneyebilirsiniz:

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

çıktı is Boolean ve stringToBool2 için çıktı: 'Boolean değil'

Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.