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

后端 未结 4 752
南旧
南旧 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:00

    I wanted to add to Brandon Moore's answer...

    So continuing from the loop...

    For x = 1 to 100
      Dim obj as New Collection
      obj.Add "New String Number " & x
    Next x
    

    Even though you've added say 20 items to obj when x = 1, when x = 2 all those 20 items will still be there! whereas, if you did set obj= new myObject then it would not! This is the most significant reason, as i once got caught out in this in a big looping area in my code, stuff was being added throughout the program and I had no idea why, nothing was being deleted or reset.

    So, If instead of:

      Dim obj as New Collection
    

    You wrote the foilowing:

      Dim obj as Collection
      Set obj = New Collection
    

    Then you would have the obj Collection being reset every single time, which is probably what you want, but if you only want it to set Once, then use the As New Collection method. But, if you jsut wanted to set it once, you'd probably put it outside the loop.

    Also, if you are not running in a loop, but the variable (Collection) is defined in a static function, or is defined with the static keyword, the exact same thing applies, not running the Set obj = New Collection will ensure you have stale data from your last use of the obj/Collection, which can be very bad.

    So, in conclusion, the two methods are actually very different (and can have different behaviour)!

提交回复
热议问题