.NET 2.0可空类型和数据库null思考

Hao*_*Hao 3 .net c# database null

如果版本1中存在.NET 2.0可空类型,那么首先不需要DBNull.Value吗?

或者RDBMS的null与.NET的null无关?无论如何,仍然需要DBNull.Value,无论.NET版本1已经具有可空类型.

Rex*_*x M 7

.NET中的可空类型允许有问题的变量实际上为null.DBNull是一种说"在另一个环境中,这个值被认为是null"的方式.因为我们需要一种方法来区分实际上为 null - 或"本机"null,就像我们当前运行时本机一样 - 并且在我们与之通信的另一个系统中为null,可空类型和DBNull服务于完全不同的目的.


Mit*_*eat 6

null并且DBNull.Value在任何.NET版本中都是两个不同的东西.

例如:

public string CustomerName(int Id)
{
   SqlCommand cmd = 
         new SqlCommand("SELECT Name FROM Customer WHERE id = " + custId, conn);

   object result = cmd.ExecuteScalar();

   if (result == null)
      return "Customer not found";

   if (result == System.DBNull.Value)
      return "Customer found but name is null";

   return (string) result;
}
Run Code Online (Sandbox Code Playgroud)

参考.