2

I'm converting some C# code to VB.NET. I have a simple dictionary-like data structure that contains name/value pairs. The value element is of type Object. My C# code looks like this

if(x.Value != null)
  // 1: Store x.Value in database
else
  // Sore DBNULL.Value in database

As expected, if x.Value happens to be a boolean of value false, code block 1 above executes.

However, the equivalent VB.NET code will fall through to the else block on a Boolean of False

If x.Value Is Not Nothing Then
  ' Store x.Value in database
Else
  ' We land here if x.Value is a Boolean with a value of False and incorrectly store DBNULL.Value in database
EndIF

VB apparently thinks a Boolean with a False value is equivalent to Nothing. I'll keep my comments about VB to myself, but is there a non-convoluted way, i.e. without using reflection, to work around this problem?

Edit: my original VB code was actually

If x.Value <> Nothing

That worked as described.

If x.Value IsNot Nothing

works correctly. Thanks Steve.

4

3 回答 3

5

您必须在 the和inIsNot之间使用没有空格。因此,您的代码将如下所示:'Is''Not'vb

If x.Value IsNot Nothing Then  
   ...do Stuff...
Else 
   ...do else stuff...
End IF
于 2015-04-17T16:03:29.770 回答
4

使用 If x.Value Is DBNull.Value Then ...

于 2013-10-16T19:55:39.187 回答
0

这是 VB.Net 的正确匹配

If Not IsNothing(x.Value) Then

但是检查空值是不同的。

于 2018-11-13T21:29:48.760 回答