簡體   English   中英

.NET 可以在沒有 If 的情況下將“Yes”和“No”轉換為布爾值嗎?

[英]Can .NET convert “Yes” & “No” to boolean without If?

你會認為有一種方法可以使用 DirectCast、TryCast、CType 等,但它們似乎都被它窒息了,例如:

CType("Yes", Boolean)

你得到:

System.InvalidCastException - 從字符串“Yes”到類型“Boolean”的轉換無效。

如果您考慮一下,“yes”不能轉換為 bool,因為它是特定於語言和上下文的字符串。

“是的”不是真實的同義詞(尤其是當你的妻子這么說時......!)。 對於這樣的事情,你需要自己轉換它; “是”的意思是“真的”,“mmmm yeeessss”的意思是“一半是真的,一半是假的,也許”等等。

使用這種方式,您可以定義從您喜歡的任何字符串到您需要的布爾值的轉換。 1是真的,0是假的,很明顯。
優點:易於修改。 您可以非常輕松地添加或刪除新別名。
缺點:可能比簡單的 if 花費的時間更長。 (但如果你有多個別名,它會變得毛茸茸的)

 enum BooleanAliases { Yes = 1, Aye = 1, Cool = 1, Naw = 0, No = 0 } static bool FromString(string str) { return Convert.ToBoolean(Enum.Parse(typeof(BooleanAliases), str)); } // FromString("Yes") = true // FromString("No") = false // FromString("Cool") = true

不,但您可以執行以下操作:

bool yes = "Yes".Equals(yourString);

C# 6+ 版本:

public static bool StringToBool(string value) => 
    value.Equals("yes",           StringComparison.CurrentCultureIgnoreCase) ||
    value.Equals(bool.TrueString, StringComparison.CurrentCultureIgnoreCase) || 
    value.Equals("1");`
private static bool GetBool(string condition)
{
    return condition.ToLower() == "yes";
}

GetBool("Yes"); // true
GetBool("No"); // false

或使用擴展方法的另一種方法

public static bool ToBoolean(this string str)
{
    return str.ToLower() == "yes";
}

bool answer = "Yes".ToBoolean(); // true
bool answer = "AnythingOtherThanYes".ToBoolean(); // false

稍微偏離主題,但我需要一次讓我的一個類在屬性網格中顯示“是/否”而不是“真/假”,所以我實現了從BooleanConverter派生的YesNoBooleanConverter並用<TypeConverter(GetType(YesNoBooleanConverter))> _ ...

你不能。 但你應該把它用作

bool result = yourstring.ToLower() == "yes";
    private bool StrToBool(string value)
    {   // could be yes/no, Yes/No, true/false, True/False, 1/0
        bool b = false;
        if (value.Equals("yes", StringComparison.CurrentCultureIgnoreCase) || value.Equals(Boolean.TrueString, StringComparison.CurrentCultureIgnoreCase) || value.Equals("1"))
        {
            b = true;
        }
        else if (value.Equals("no", StringComparison.CurrentCultureIgnoreCase) || value.Equals(Boolean.FalseString, StringComparison.CurrentCultureIgnoreCase) || value.Equals("0"))
        {
            b = false;
        }
        else
        {   // we should't be here 
            b = false;
        }
        return b;
    }

我喜歡@thelost 發布的答案,但我正在從 ADO.Net DataTable 讀取值,並且 DataTable 中字符串的大小寫可能會有所不同。

我需要作為布爾值獲取的值位於名為Trades的列中名為childAccounts的數據childAccounts中。

我實現了這樣的解決方案:

bool tradeFlag = childAccounts["Trade"].ToString().Equals("yes", StringComparison.InvariantCultureIgnoreCase);
public static bool IsBoolean(string strValue)
{
    return !string.IsNullOrEmpty(strValue) && ("1/YES/TRUE".IndexOf(strValue, StringComparison.CurrentCultureIgnoreCase) >= 0);
}

我喜歡為此switch ,因為它簡單且可根據需要輕松擴展。 默認模式可以毫不費力地捕獲空字符串和空值。 我也喜歡擴展方法,所以我最終得到了這個:

public static class StringExtensions
{
    public static bool ToBool(this string str)
    {
        return str?.ToLower() switch
        {
            "true" => true,
            "yes" => true,
            "y" => true,
            "t" => true,
            "1" => true,
            _ => false
        };
    }   
}

用法

"Yes".ToBool();  // true
"no".ToBool();   // false
"".ToBool();     // false

string s = null;
s.ToBool();      // false

這是完成此操作的簡單方法。

rv.Complete = If(reader("Complete") = "Yes", True, False)
Public Function TrueFalseToYesNo(thisValue As Boolean) As String
    Try
        If thisValue Then
            Return "Yes"
        Else
            Return "No"
        End If
    Catch ex As Exception
        Return thisValue.ToString
    End Try
End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM