What is the reason for not instantiating an object at the time of declaration?

后端 未结 4 771
南旧
南旧 2020-12-01 16:09

I had to delve into some VB6 code recently and I saw this pattern all over the place:

dim o as obj
set o = new obj

Why not this?

         


        
4条回答
  •  感动是毒
    2020-12-01 17:04

    There may be other reasons but in VB6 using the New keyword when you Dim an object can cause unexpected results because VB will instantiate the object whenever it is referenced.

    Dim objMyObject as New SomeObject
    
    Set objMyObject = Nothing   ' the object is nothing
    
    If objMyObject Is Nothing Then  ' referencing the object instantiates again
       MsgBox "My object is destroyed"  ' what you would probably expect
    Else
       MsgBox "My object still exists"
    End If
    

提交回复
热议问题