应该使用IsDBNull和IsNull中的哪个? [英] Which of IsDBNull and IsNull should be used?

查看:143
本文介绍了应该使用IsDBNull和IsNull中的哪个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在 VB.NET 中,我有 DataRow ,我想测试列值是否为 Null ,我应该使用:

If in VB.NET I have DataRow and I want to test whether a column value is Null, should I use:

myDataRow.IsNull("Column1")

OR

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.

长答案 :(您需要阅读C#代码才能理解此部分; MS使用C#提供了框架代码,但是VB程序员应该能够

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)

以下是 IsNull 调用内部发生的情况DataRow

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);
}

列。IsNull执行快速断言,并将调用转发到内部类 DataStorage

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);
}

最后,这是 _storage.IsNull 确实:

public virtual bool IsNull(int recordNo) {
    return this.dbNullBits.Get(recordNo);
}

因为 dbNullBits 是一个 BitArray ,该操作很快完成。

Since dbNullBits is a BitArray, this operation completes very quickly.

现在考虑一下索引器 myDataRow( Column1)做(在将其结果传递给 IsDBNull 之前,请调用此索引器):

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];
}

请注意, IsNull的前两行方法和索引器相同。但是,接下来的三行需要执行验证,并获取值本身。只有在此之后,您的代码才能开始计算其目标值-一个标志,该标志告诉它目标值是否为 DBNull 。这需要更多的计算,但更重要的是,每次执行检查时都需要进行一些计算。这比使用预先计算的值要慢。

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.

这篇关于应该使用IsDBNull和IsNull中的哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆