null 和 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 数据读取器从数据库中检索数据,但没有返回值 if(rdr["Id"] != null)
返回 true
和最终抛出一个异常,将 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.
但是,如果我使用 if (rdr["Id"] != System.DBNull.Value)
返回 false
.
But, this if I use if (rdr["Id"] != System.DBNull.Value)
returns false
.
null 和 System.DBNull.Value 有什么区别?
What's the difference between null and System.DBNull.Value?
好吧,null
不是任何类型的实例.相反,它是一个无效的引用.
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
为您提供对该类的单个实例的引用),该实例表示数据库中不存在的* 值.
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.
*我们通常会说null
,但我不想混淆这个问题.
*We would normally say null
, but I don't want to confound the issue.
因此,两者在概念上存在很大差异.关键字 null
表示无效的引用.System.DbNull
类表示数据库字段中不存在的值.一般来说,我们应该尽量避免使用相同的东西(在本例中为 null
)来表示两个截然不同的概念(在本例中是无效引用与数据库字段中不存在的值).
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.
这篇关于null 和 System.DBNull.Value 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!