这里有人使用VB.NET,是否强烈偏爱使用Not foo Is Nothing
而不是foo IsNot Nothing
?如果是,为什么?
例如:
If var1 IsNot Nothing Then
...
End If
和
If Not var1 Is Nothing Then
...
End If
我只是想知道哪个更好?
它们两个都一样可接受吗?
这里有人使用VB.NET,是否强烈偏爱使用Not foo Is Nothing
而不是foo IsNot Nothing
?如果是,为什么?
例如:
If var1 IsNot Nothing Then
...
End If
和
If Not var1 Is Nothing Then
...
End If
我只是想知道哪个更好?
它们两个都一样可接受吗?
The
If Not var1 Is Nothing Then
这是VB6的遗留问题。以前没有 IsNot 这个关键字,所以这是唯一确定变量是否不是 Nothing
的方法。在VB.NET中似乎是多余的。
Not x Is Nothing
首先进行类型相等性检查,然后否定它。而 x IsNot Nothing
只进行类型不相等性检查,运行时可能能够更快地完成(可以愚蠢地想象为它逐个字段地检查类型字段,并在第一个不匹配的字段处退出,而不是通过每个字段来检查相等性 - 最终只需否定结果)。 - Ray我会选择第一种变体——它读起来就像英语,比第二种容易跟踪/理解。除此之外,它们是相等的。
我在这里找到了一个类似的问题VB.NET - IsNothing versus Is Nothing,我觉得这个问题已经得到详细解答。在回答中,Jack Snipes指出了一篇博客文章http://weblogs.asp.net/psteele/410336,提供了一些额外的细节信息。从这些回答中,我更喜欢并使用了
IsNot Nothing
这也使得我的代码更易于阅读和理解。
使用VB 7.0
If var1不是Nothing Then
根据"VBForums"链接,会生成“无效的对象错误”。
If var1 IsNot Nothing Then
会生成“编译错误:预期:Then或GoTo”
If Not IsNothing(var1) Then
像个冠军一样工作了。
var1 IsNot Nothing Then
后面没有语句或代码块,会产生编译错误。var1 IsNot Nothing
本身是可以工作的。您还未展示Not var1 Is Nothing
的作用,因此并未真正回答问题。请修复您的格式。 - Breeze