How to convert “0” and “1” to false and true

前端 未结 9 661
無奈伤痛
無奈伤痛 2021-02-06 19:59

I have a method which is connecting to a database via Odbc. The stored procedure which I\'m calling has a return value which from the database side is a \'Char\'. Right now I\'

相关标签:
9条回答
  • 2021-02-06 20:46

    If you want the conversion to always succeed, probably the best way to convert the string would be to consider "1" as true and anything else as false (as Kevin does). If you wanted the conversion to fail if anything other than "1" or "0" is returned, then the following would suffice (you could put it in a helper method):

    if (returnValue == "1")
    {
        return true;
    }
    else if (returnValue == "0")
    {
        return false;
    }
    else
    {
        throw new FormatException("The string is not a recognized as a valid boolean value.");
    }
    
    0 讨论(0)
  • 2021-02-06 20:46

    You can use that form:

    return returnValue.Equals("1") ? true : false;
    

    Or more simply (thanks to Jurijs Kastanovs):

    return returnValue.Equals("1");
    
    0 讨论(0)
  • 2021-02-06 20:53

    Set return type to numeric - you don't need a char (so don't use it); a numeric value (0/1) can be converted with Convert.ToBoolean(num)

    Otherwise: use Kevin's answer

    0 讨论(0)
提交回复
热议问题