What is the difference between 'foo = Nothing' and 'foo is Nothing' in VB.NET?

后端 未结 6 864
醉梦人生
醉梦人生 2021-01-02 07:12

In VB.NET, what is the difference between

if foo is Nothing Then
      doStuff()
End If

and

if foo=Nothing Then
    doStuff         


        
6条回答
  •  借酒劲吻你
    2021-01-02 07:29

    foo is a pointer to a memory location and Nothing means 'not pointing to any memory because no memory has been allocated yet'. Equals means that when you are comparing 2 value types they have the same value. But you're assuming foo represents an object, which is always a reference type that is meant to point to an object in memory. 'is' is for comparing object types and will only return 'true' if you have two objects pointing to the same value.

    Say you have clsFoo with one public integer member variable 'x' and foo1 and foo2 are both clsFoo, and y and z are integers

    foo1=new clsFoo
    foo2=new clsFoo
    foo1.x=1
    foo2.x=1
    y=2
    z=1
    dim b as boolean 
    
    b= foo1 is not foo2  ' b is true
    b= foo1.x=foo2.x ' b is tree
    b= foo1 is foo2 'b is false  
    b= foo1.x=z ' true of course
    foo2.x=3
    b= foo1.x=foo2.x ' false of course
    foo1=foo2
    b=foo1 is foo2 ' now it's true
    b= foo1.x=foo2.x ' true again
    b= 3=3 ' just as this would be
    b= foo1=foo2 ' ERROR: Option Strict On disallows operands of type Object for operator '='. Use the 'Is' operator to test for object identity.
    

    NEVER forget to turn option strict on. To fail this is to scream 'PLEASE make my program SUCK.'

提交回复
热议问题