开发者

VB.NET IsNot for string comparison

If 开发者_如何转开发Object.Value IsNot "Something" Then

Can you do this, or are there certain cases in which it wouldn't work? Wasn't sure if this should only be used for integers and booleans.

Thanks!


I'm not sure if this works or not but if it did it would be a very bad idea to use. The Is and IsNot operators in VB.Net do reference comparisons. When dealing with String values you almost always want to do a value comparison which is through = and <>.

Reference comparisons tell you if it's literally pointing to the same object. In .Net it's very possible for the same identical string to be captured in 2 objects allowing for confusing cases like the following

Function CreateFoo() As String
  return "foo"
End Function

Dim str1 = "foo"
Dim str2 = CreateFoo()
if str1 Is str2 Then
  ' This is possible
Else
  ' This is also possible
End If

Value comparison provides much more sanity here

Dim str1 = "foo"
Dim str2 = CreateFoo()
if str1 = str2 Then
  ' This will run
Else
  ' This is simply not possible
End If


That is will tell you if Object.Value and "Something" are literally the same object.

99.999% of the time, you don't care about that. All you care about is if they are semantically equal, that is they both contain the word 'Something'.


From the documentation: "The IsNot operator determines if two object references refer to different objects."

Thus, you would not want to compare strings with it because it is unlikely that two identical strings would actually refer to the same object. This would only happen if they were compile-time constants, were interned, or both copies of the same variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜