如何将“0”和“1”转换为“假”和“真”

我有一个通过 Odbc 连接到数据库的方法 调用有一个返回值,从数据库端是一个“ Char” 将返回值作为一个字符串并在一个简单的 if 语句中使用它 当只能从数据库返回0和1两个值时,比较这样的字符串。

OdbcCommand fetchCommand = new OdbcCommand(storedProc, conn);


fetchCommand.CommandType = CommandType.StoredProcedure;
fetchCommand.Parameters.AddWithValue("@column ", myCustomParameter);
fetchCommand.Parameters.Add("@myReturnValue", OdbcType.Char, 1)
.Direction = ParameterDirection.Output;
fetchCommand.ExecuteNonQuery();


string returnValue = fetchCommand.Parameters["@myReturnValue"].Value.ToString();
if (returnValue == "1")
{
return true;
}

处理这种情况的正确方法是什么 但是我遇到了‘字符串不被认为是一个有效的布尔值。异常被抛出。我是不是错过了什么 在这里,或者有其他方法使’1’和’0’表现得像真和假?

谢谢!

224043 次浏览

How about:

return (returnValue == "1");

or as suggested below:

return (returnValue != "0");

The correct one will depend on what you are looking for as a success result.

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

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

In a single line of code:

bool bVal = Convert.ToBoolean(Convert.ToInt16(returnValue))

Or if the Boolean value is not been returned, you can do something like this:

bool boolValue = (returnValue == "1");
(returnValue != "1" ? false : true);

You can use that form:

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

Or more simply (thanks to Jurijs Kastanovs):

return returnValue.Equals("1");

If you don't want to convert.Just use;

 bool _status = status == "1" ? true : false;

Perhaps you will return the values as you want.

My solution (vb.net):

Private Function ConvertToBoolean(p1 As Object) As Boolean
If p1 Is Nothing Then Return False
If IsDBNull(p1) Then Return False
If p1.ToString = "1" Then Return True
If p1.ToString.ToLower = "true" Then Return True
Return False
End Function