可以使用?? (聚结运营商)与DBNull的? [英] Possible to use ?? (the coalesce operator) with DBNull?

查看:123
本文介绍了可以使用?? (聚结运营商)与DBNull的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有code类似以下内容:

If I have code similar to the following:

while(myDataReader.Read())
{
  myObject.intVal = Convert.ToInt32(myDataReader["mycolumn"] ?? 0);
}

这引发错误:

It throws the error:

对象不能从DBNull转换为其他类型。

Object cannot be cast from DBNull to other types.

定义 INTVAL 作为一个可空int是不是一种选择。有没有办法为我做以上?

defining intVal as a nullable int is not an option. Is there a way for me to do the above?

推荐答案

你能使用的扩展方法? (注销我的头顶部)

Can you use an extension method? (written off the top of my head)

public static class DataReaderExtensions 
{
    public static T Read<T>(this SqlDataReader reader, string column, T defaultValue = default(T))
    {
        var value = reader[column];

        return (T)((DBNull.Value.Equals(value))
                   ? defaultValue
                   : Convert.ChangeType(value, typeof(T)));
    }
}

您会使用它,如:

while(myDataReader.Read())
{
  int i = myDataReader.Read<int>("mycolumn", 0);
}

这篇关于可以使用?? (聚结运营商)与DBNull的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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