I'm reading in data from a sqlite reader. It's returning an object
, most of them I know are boolean
. What's the best way to convert object
into a boolean
?
I would probably go through TryParse
. Otherwise you run the risk of throwing an exception. But it depends on how your system is written.
object x;
bool result = false;
if(bool.TryParse(string.Format("{0}", x), out result))
{
// do whatever
}
Alternatively you can do a direct cast:
bool result = (bool)x;
Or use the Convert
class:
bool result = Convert.ToBoolean(x);
Or you can use a Nullable<bool>
type:
var result = x as bool?;
In this case, you'll probably want the as operator . Keep in mind, your type would be a bool?
.
Like this:
bool? val = YourValue as bool?;
if (val != null)
{
....
}
尝试转换它。
var boolValue = (bool)yourObject;
If you want case an object to a boolean type, you simply need to check if the object is
a bool, then cast it, like so:
if (someObject is bool)
{
bool someBool = (bool)someObject;
...
}
As a side note, it is not possible to use the as
operator on a non-reference type (because it cannot be null). This question may be a duplicate of this one.
If you must have a final bool
value, for C# 7.0 (introduced in 2017) and later, a compact syntax is:
bool myBool = (myObject as bool?) ?? false;
So this might be "best" from the standpoint of brevity. But code using the is
operator performs better (see here ). In this case, the following may be preferred:
bool myBool = myObject is bool ? (bool)myObject : false;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.