Store Variable Name in String in VB.NET

旧城冷巷雨未停 提交于 2020-01-02 06:57:09

问题


I'm trying to store the names of some variables inside strings. For example:

Dim Foo1 as Integer
Dim Foo1Name as String

' -- Do something to set Foo1Name to the name of the other variable --

MessageBox.Show(Foo1Name & " is the variable you are looking for.")
' Outputs:
' Foo1 is the variable you are looking for.

This would help with some debugging I'm working on.


回答1:


Well, you can clearly just set Foo1Name = "Foo1" - but I strongly suspect that's not what you're after.

How would you know which variable you're trying to find the name of? What's the bigger picture? What you want may be possible with reflection, if we're talking about non-local variables, but I suspect it's either not feasible, or there's a better way to attack the problem in the first place.




回答2:


Does this example from msdn using reflection help?




回答3:


One solution would be to use an associative array to store your variables. Once, I did this in .Net, but I think I wrote a custom class to do it.

myArray("foo1Name") = "foo1"

Then, you can just store a list of your variable names, or you can wrap that up in the same class.

if( myArray(variableName(x)) == whatImLookingFor ) print variableName(x) & "is it"



回答4:


I think this really depends on what you are trying to debug. Two possible things to look at are the Reflection and StackTrace classes. That said when your program is compiled, the compiler and runtime do not guarantee that that names need to be consistent with the original program.

This is especially the case with debug vs. release builds. The point of the .PDB files (symbols) in the debug version are to include more information about the original program. For native C/C++ applications it is strongly recommended that you generate symbols for every build (debug+release) of your application to help with debugging. In .NET this is less of an issue since there are features like Reflection. IIRC John Robbins recommends that you always generate symbols for .NET projects too.

You might also find Mike Stall's blog useful and the managed debugger samples.




回答5:


For finding the variable name, see: Finding the variable name passed to a function

This would apply to VB.Net as well.



来源:https://stackoverflow.com/questions/353131/store-variable-name-in-string-in-vb-net

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