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

后端 未结 12 635
情话喂你
情话喂你 2020-12-17 14:15

You would think there would be a way using DirectCast, TryCast, CType etc but all of them seem to choke on it e.g.:

CType(\"Yes\", Boolean)

相关标签:
12条回答
  • 2020-12-17 15:01

    No, but you could do something like:

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

    0 讨论(0)
  • 2020-12-17 15:02
    public static bool IsBoolean(string strValue)
    {
        return !string.IsNullOrEmpty(strValue) && ("1/YES/TRUE".IndexOf(strValue, StringComparison.CurrentCultureIgnoreCase) >= 0);
    }
    
    0 讨论(0)
  • 2020-12-17 15:03
        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;
        }
    
    0 讨论(0)
  • 2020-12-17 15:07

    Here is a simple way to get this done.

    rv.Complete = If(reader("Complete") = "Yes", True, False)
    
    0 讨论(0)
  • 2020-12-17 15:08

    You Can't. But you should use it as

    bool result = yourstring.ToLower() == "yes";
    
    0 讨论(0)
  • 2020-12-17 15:12
    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
    
    0 讨论(0)
提交回复
热议问题