什么是零和System.DBNull.Value之间的区别? [英] What is the difference between null and System.DBNull.Value?

查看:94
本文介绍了什么是零和System.DBNull.Value之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有空和System.DBNull.Value有什么区别?如果有,是什么?

Is there any difference between null and System.DBNull.Value? If yes, what is it?

我现在发现这种行为 -

I noticed this behavior now -

while (rdr.Read())
{
    if (rdr["Id"] != null) //if (rdr["Id"] != System.DBNull.Value)  
    {
        int x = Convert.ToInt32(rdr["Id"]);
    }
}

虽然我使用SQL DataReader的,虽然没有返回值从数据库中检索数据如果(RDR [ID]!= NULL)返回真正,并最终引发了异常铸造一个空的整数。

While I retrieve data from the database using a sql datareader, though there is no value returned if(rdr["Id"] != null) returned true and eventually threw an exception for casting a null as integer.

但是,这如果我使用如果(RDR [ID]!= System.DBNull.Value)收益

But, this if I use if (rdr["Id"] != System.DBNull.Value) returns false.

有什么空和System.DBNull.Value之间的区别?

What's the difference between null and System.DBNull.Value?

推荐答案

好了,不是任何类型的实例。相反,它是一个无效的参考

Well, null is not an instance of any type. Rather, it is an invalid reference.

然而, System.DbNull.Value ,是 System.DbNull 的一个实例(一个有效的参考 System.DbNull 是一个单和 System.DbNull.Value 为您提供了这个类的一个实例的引用)的再presents不存在 * 值在数据库中。

However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database.

*我们通常会说,但我不想混淆的问题。

*We would normally say null, but I don't want to confound the issue.

所以,有在两者之间有很大概念上的差异。关键字重新presents无效引用。类 System.DbNull 重新presents在数据库字段不存在的价值。一般情况下,我们应该尽量避免使用同样的事情(在这种情况下,)重新present两个非常不同的概念(在这种情况下,一个无效的引用与一个不存在的在数据库字段值)。

So, there's a big conceptual difference between the two. The keyword null represents an invalid reference. The class System.DbNull represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).

请记住,这就是为什么很多人主张用一般空对象模式,而这正是什么 System.DbNull 是一个例子。

Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull is an example of.

这篇关于什么是零和System.DBNull.Value之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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