16

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

我希望将此值存储Nullable<bool>在 C# 中的类型变量中。

我似乎无法找到可接受的显式转换和转换组合,它们以简单的方式执行此操作而不会引发异常。

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

编辑:按要求编码

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

也许

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

5 回答 5

11

假设你有一个数据阅读器博士:

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

- -添加 - -

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

bool? tmp = dr["dbnullValue"] ?? (bool?) dr["dbnullValue"];
于 2013-01-30T17:31:17.293 回答
6

你可以写value as bool?。如果不是 type ,
这将返回。nullvaluebool

请注意,这有点低效

于 2013-01-30T17:21:46.500 回答
0
 while (reader.Read()) {
    bool? IsRestricted = (reader.IsDBNull(reader.GetOrdinal("IsRestricted"))) ? (null) : ((bool)reader.GetOrdinal("IsRestricted")));
 }
于 2013-01-30T19:59:39.413 回答
0

我使用扩展方法来解决这个问题。

var isRestricted = dataRecord.GetNullableValue<bool>("IsRestricted");

有 GetNullableValue 方法的代码:

    public static Nullable<TValue> GetNullableValue<TValue>(
        this IDataRecord record, 
        string name) where TValue : struct
    {
        return record.GetValue<TValue, Nullable<TValue>>(name);
    }

GetValue 方法还有一个简单的代码:

        private static TResult GetValue<TValue, TResult>(
        this IDataRecord record,
        string name)
    {
        var result = record[name];
        return !result.Equals(DBNull.Value) ? (TResult)result : default(TResult);
    }
于 2013-01-30T20:30:34.227 回答
0

您可以执行以下操作

bool? myNullableBoolean = SqlConvert.ToType<bool?>(reader["myNullableBooleanColumn"]);

于 2019-12-18T12:58:53.617 回答