C# equivalent for Visual Basic keyword: 'With' … 'End With'?

后端 未结 7 1948
南笙
南笙 2020-12-11 04:21

In Visual Basic, if you are going to change multiple properties of a single object, there\'s a With/End With statement:

Dim myObject as Object

         


        
7条回答
  •  攒了一身酷
    2020-12-11 04:39

    If the "with" expression is a class type, the "With" statement is equivalent to creating a new temporary variable of that type, initialized to the "With" expression, and preceding each leading "." with that variable. If it is a structure type, however, things are more complicated. Consider the code (obviously not the way one would normally write something, but written as it is to make a point:

      With MyPoints(N) ' Array of Point
        N=SomeNewValue
        .X = MyPoints(N).X
        .Y = MyPoints(N).Y
      End With
    

    The "With" statement effectively latches a reference to MyPoints(N). Even if MyPoints is changed to some other array, or N is changed, the latched reference will still point to the same element of the same array as it did when the With statement was executed. If one declared a local variable P of type Point and grabbed MyPoints(N), and then write to P.X and P.Y, the writes would only hit the local copy P, rather than updating the array. To achieve similar semantics in C#, one would have to either use local variables to hold both MyPoints and N, or else place the contents of the With statement within an anonymous function which has a ref parameter of type Point. To avoid having to create a closure at run-time, the anonymous function should also accept, probably by reference, any local variables it will need from the outer scope.

提交回复
热议问题