VB.Net - “With” and Closures don't mix

后端 未结 2 1104
走了就别回头了
走了就别回头了 2021-01-12 08:56

Just thought I\'d share this in case anyone else has run into this.
I did something similar today and it took me a while to figure out why this was causing a problem at

相关标签:
2条回答
  • 2021-01-12 09:33

    There's really only one bug that I see, the compiler should generate an error for this. Shouldn't be hard to implement. You can report it at connect.microsoft.com

    0 讨论(0)
  • 2021-01-12 09:50

    This behavior is "By Design" and results from an often misunderstood detail of the With statement.

    The With statement actually takes an expression as an argument and not a direct reference (even though it's one of the most common use cases). Section 10.3 of the language spec guarantees that the expression passed into a With block is evaluated only once and is available for the execution of the With statement.

    This is implemented by using a temporary. So when executing a .Member expressio inside a With statement you are not accessing the original value but a temporary which points to the original value. It allows for other fun scenarios such as the following.

    Dim o as New Foo
    o.bar = "some value"
    With o   
      o = Nothing
      Console.WriteLine(.bar) ' Prints "some value"
    End With
    

    This works because inside the With statement you are not operating on o but rather a temporary pointing to the original expression. This temporary is only guaranteed to be alive for the lifetime of the With statement and is hence Nothingd out at the end.

    In your sample the closure correctly captures the temporary value. Hence when it's executed after the With statement completes the temporary is Nothing and the code fails appropriately.

    0 讨论(0)
提交回复
热议问题