null 和 System.DBNull.Value 有什么区别?
- 作者: 郝天源大少爷
- 来源: 51数据库
- 2022-10-20
问题描述
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.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
