我可以在一行中从 DBNull 转换为 Nullable Bool 吗? [英] Can I cast from DBNull to a Nullable Bool in one line?

查看:55
本文介绍了我可以在一行中从 DBNull 转换为 Nullable Bool 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库查询,它将返回 NULL 或一个布尔值(位).

I have a database query which will either return NULL or a boolean (bit) value.

我希望将此值存储在 C# 中 Nullable 类型的变量中.

I wish to store this value in a variable of type Nullable<bool> in C#.

我似乎无法找到一种可接受的显式强制转换和转换的组合,以简单的方式做到这一点而不会抛出异常.

I can't seem to find an acceptable mix of explict casts and conversions that do this in a simple way without Exceptions being thrown.

可以在一个可读的行中完成吗?

Can it be done in one readable line?

按要求编码

private Nullable<bool> IsRestricted;
...//data access
IsRestricted = (bool?)DataBinder.GetPropertyValue(dataObj, "IsRestricted");

也许

IsRestricted = (bool?)(bool)DataBinder.GetPropertyValue(dataObj, "IsRestricted");

推荐答案

假设你有一个 datareader dr:

assuming you have a datareader dr:

bool? tmp = Convert.IsDBNull(dr["dbnullValue"]) ? null: (bool?) dr["dbnullValue"];

---添加---

或者也许你可以使用 ??如果您不必检查 DBNull 但我不确定编译器会喜欢这个(我现在无法测试)

or maybe you can use the ?? if you don't have to check for DBNull but i'm not sure compiler will like this (i cannot test it now)

bool? tmp = dr["dbnullValue"] ?? (bool?) dr["dbnullValue"];

这篇关于我可以在一行中从 DBNull 转换为 Nullable Bool 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆