如果VB.NET
我有DataRow
并且我想测试列值是否为Null
,我应该使用:
myDataRow.IsNull("Column1")
或者
IsDBNull(myDataRow("Column1"))
Short answer: use the first way, it is faster, because the first method uses a pre-computed result, while the second method needs to recompute it on the fly every time you call it.
Long answer: (you need to read C# code to understand this part; MS supplies framework code in C#, but VB programmers should be able to get the general idea of what's going on)
Here is what happens inside the IsNull
call of DataRow
:
public bool IsNull(string columnName) {
DataColumn column = GetDataColumn(columnName);
int record = GetDefaultRecord();
return column.IsNull(record);
}
The column.IsNull
performs a quick assertion, and forwards the call to DataStorage
, an internal class:
internal bool IsNull(int record) {
Debug.Assert(null != _storage, "no storage");
return _storage.IsNull(record);
}
Finally, here is what _storage.IsNull
does:
public virtual bool IsNull(int recordNo) {
return this.dbNullBits.Get(recordNo);
}
Since dbNullBits
is a BitArray
, this operation completes very quickly.
Now consider what the indexer myDataRow("Column1")
does (you call this indexer before passing its result to IsDBNull
):
get {
DataColumn column = GetDataColumn(columnName);
int record = GetDefaultRecord();
_table.recordManager.VerifyRecord(record, this);
VerifyValueFromStorage(column, DataRowVersion.Default, column[record]);
return column[record];
}
Note that the first two lines of IsNull
method and the indexer are identical. However, the three rows that follow need to perform validation, and fetch the value itself. Only after that your code can start computing its target value - a flag that tells it if the value is DBNull
or not. This requires more computation, but more importantly, it requires some computation every time you perform the check. This is slower than using a pre-computed value.
.NET 几乎从不会意外地为您提供两种方法来做同样的事情。DataRow.IsNull() 更有效,它避免了必须检索列值然后检查 IsDBNull。在内部,它已经跟踪列是否为空,由创建行时确定。所以 IsNull() 可以很快地给你。因此,它应该是您的偏好。
我做了一些调查,发现了一些有趣的事实,这些事实为DataRow.IsNull
OR的使用提供了更多的见解IsDBNull
。
DataRow.IsNull - 获取一个值,该值指示指定的 DataColumn 是否包含空值。Convert.IsDBNull - 返回指定对象是否为 DBNull 类型的指示。
参考资料:DataRow.IsNull和IsDBNull
提供明确结论的最有趣的讨论可以从性能考虑中得出
之前进行了几乎类似的讨论,以下是参考:
在处理 DataRow 数据时,最好使用 IsDBNull() 函数。IsDBNull() 的优点是它检查您的对象是否表示null,而不是简单地为 null 本身,这是一个重要的区别。当您查询数据库中为空的数据行项目时,项目本身作为对象存在,但它表示一个 NULL 值。如果你使用 IsNull() 你会错过 NULL 值。
From a database design and usage point of view, IsNull is the correct and accepted way to interrogate the value of a column, based on use of various database technologies including SQL, DB2, OLAP, MOLAP, RDBMS, MDBMS, SPSS, Essbase, etc. By definition Null is the absence of a value, a unknown, and Null is not even equal to Null, so any adjunct to Null is just a matter of convenience.
使用IsDBNull
IsNull 与 IsDBNull 略有不同。一个检查使用的数据库中的 DB Null 值,另一个检查 Null。
我会一直使用myDataRow.IsNull("Column1")
,因为在发出 a 时SELECT
,如果值是null
它,它会返回为null
而不是DBNull
。