Is there a way to debug VB.NET With clause in Visual Studio?

限于喜欢 提交于 2019-12-18 08:29:58

问题


Sometimes you don't really care about the name of a variable, because it does not go outside of your sub's scope. In fact, specifying the name would add an extra line of code. Also now you have this name to deal with, which may add to potential refactoring effort (if you decide to rename it later). Have a look at the code below:

Dim fileInfo As New FileInfo("filename.txt")
With New FileSystemWatcher
  .Path = fileInfo.DirectoryName
  .Filter = fileInfo.Name
  .EnableRaisingEvents = True
  AddHandler .Changed, AddressOf OnChanged
End With

It is a perfectly valid VB.NET construct, which looks neat and clean. However, when it comes to debugging, and assuming you put a breakpoint inside the With clause, there is no option to grab that .Path to make sure it was set properly.

Am I missing anything here or does Visual Studio really not provide debugging for .Property syntax inside With statements? I am using 2010.

Obviously, there is not much to debug in the above code, but there can be numerous examples of when such nameless With approach would come handy.

BTW, named With clauses have the same problem, i.e. if I was to write:

Dim fsw As New FileSystemWatcher
With fsw
  .Path = fileInfo.DirectoryName
  .Filter = fileInfo.Name
  .EnableRaisingEvents = True
  AddHandler .Changed, AddressOf OnChanged
End With

I still cannot pull the value of .Path, having to always prefix it with fsw.

The problem grows in size as you nest With clauses in one another.


回答1:


The With statement with an unnamed variable is a formidable challenge for the debugger, there's no workaround for it. There's just nothing wrong with a small named helper variable like "fsw", it exists anyway, auto-generated by the compiler. Which is not nameless, just unspeakable. Like VB$t_ref$L0), the debugger won't let you type that in since it uses characters that are not valid in VB.NET identifier names. Which is intentional, it ensures it never collides with a name that you used. This also prevents it from showing up in the Autos window.

You already found the proper workaround by naming the variable. Debugging from there is simple, just hover the mouse over the variable name, not the field name. And of course works well in all the other debugger windows, the Autos window in particular will spring to life. And don't hesitate to drop the With statement in favor of just writing the statement in full, IntelliSense helps a lot to make this less of a chore.




回答2:


An option would be to add those variables to the watch list instead, and view the values from the watch window.



来源:https://stackoverflow.com/questions/15256776/is-there-a-way-to-debug-vb-net-with-clause-in-visual-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!