DBNull 到底有什么用?
可能的重复:
DBNull 的意义是什么?
自从我开始 .NET 冒险以来我总是问自己一个问题:
为什么我们需要 DBNull 类型?简单的空引用还不够吗?
MSDN 说 DBNull“代表一个不存在的值”。从逻辑的角度来看——这句话解释了为什么不能使用空引用——因为它是空引用而不是缺少值。但是引入一种会带来很多麻烦的类型就足够了吗?
顺便说一句:如果有人有话要说来捍卫 DBNull,我将非常感激。
Possible Duplicate:
What is the point of DBNull?
Since the beginning of my adventure with .NET I have always asked myself one question:
why do we need the DBNull type? Is a simple null reference not enough?
MSDN says that DBNull "Represents a nonexistent value". From a logical point of view - this one sentence explains why a null reference cannot be used - because it is a null reference and not a lack of value. But is it enough to introduce a type that causes a lot of trouble?
BTW: If anyone has something to say in defense of the DBNull
I would really appreciate it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
DBNull 自.Net 框架的最早版本。
可空值类型 (
Nullable;
)自该框架的第 2 版以来才存在。因为在版本 2 之前,可以从数据库接收一个 null int 值,您建议如何表示它?然后,为了保持一致性,使用相同的值来表示所有数据库空值,无论它们转换为值还是引用类型。
DBNull has existed since the earliest versions of .Net framework.
Nullable value types (
Nullable<T>
) has only existed since version 2 of the framework.Since, before version 2, it was possible to receive, say, a null int value back from the database, how would you propose it be represented? Then, for consistency, the same was used to represent all DB nulls, whether they translated to a value or reference type.
DBNull.Value
表示数据库中的“NULL”;它与“null”不同。DBNull.Value
represents 'NULL' in the database; it is not the same as 'null'.我们需要它来检测从数据库返回的值是否为空。
通常,
Convert.IsDBNull
用于执行检查。DBNull
类型与编程值null
不同We need it so we can detect if a value returned from a database is null or not.
Typically,
Convert.IsDBNull
is used to perform the check.The
DBNull
type is not the same as the programming valuenull
C# 中的 null 与 SQL 上下文中的 NULL 不同,C# 中的 SQL NULL 不是作为字符串公开,而是作为
DbNull.Value
公开,这是有道理的,如果不是这样,您将如何检查数据库为空?比较字符串"NULL"
不会相同...null in c# is something different than NULL in the SQL context, the SQL NULL in C# is exposed not as string but as
DbNull.Value
which makes sense, if it was not like that how would you check for db null? comparing a string"NULL"
would not have been the same...