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

后端 未结 10 2459
感动是毒
感动是毒 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:05

    Where it makes the code genuinely more readable, go for it. Where it makes it less readable, avoid it - in particular, I suggest you avoid nesting With statements.

    C# 3.0 has this feature solely for object initialization:

    var x = new Whatever { PropertyA=true, PropertyB="Inactive" };
    

    This is not only pretty much required for LINQ, but it also makes sense in terms of where the syntax doesn't indicate a code smell. I usually find that when I'm performing many different operations on an object beyond its initial construction, those operations should be encapsulated as a single one on the object itself.

    One note about your example - do you really need the "Me" at all? Why not just write:

    PropertyA = True
    PropertyB = "Inactive"
    

    ? Surely "Me" is implied in that case...

提交回复
热议问题