The VB.NET 'With' Statement - embrace or avoid?

后端 未结 10 2485
感动是毒
感动是毒 2020-11-29 02:53

At work, I\'m frequently working on projects where numerous properties of certain objects have to be set during their construction or early during their lifetime. For the sa

10条回答
  •  一个人的身影
    2020-11-29 03:11

    There is a difference between using With and making repeating references to an object, which is subtle but should be borne in mind, I think.

    When a WITH statement is used, it creates a new local variable referencing the object. Subsequent references using .xx are references to properties of that local reference. If during the execution of the WITH statement, the original variable reference is changed, the object referenced by the WITH does not change. Consider:

    Dim AA As AAClass = GetNextAAObject()
    With AA
        AA = GetNextAAObject()
    
        '// Setting property of original AA instance, not later instance
        .SomeProperty = SomeValue
    End With
    

    So, the WITH statement is not simply syntactical sugar, it is genuinely a different construct. Whilst you would be unlikely to code something explicit like the above, in some situations this might occur inadvertently so you should be aware of the issue. The most likely situation is where you may be traversing a structure such as a network of objects whose interconnections my be implicitly changed by setting properties.

提交回复
热议问题