简体   繁体   中英

php $$var equivalent in vb.net (vb2010)

I am writing a program in VB.NET and I need to get to a variable whose string value is gotten dynamically. Just like in PHP:

$text = "new_var" (gotten dynamically)

$$text = 100

I want to do this in VB.NET.

The direct equivalent in VB.NET is called reflection . Reflection allows you to inspect the names of types and their members at run-time. However, it should typically only be used as a last resort. Often when switching languages, the direct equivalent is not the best option, since the paradigms are different. Even if you did use reflection, it does not work for local variables, so you would likely need to substantially redesign your code anyway.

The better solution would probably be to use a Dictionary object. The Dictionary class in .NET is an implementation of a hash-table which allows you to easily store key/value pairs. So, instead of storing the value in a variable, you could store it in a Dictionary , like this:

Dim d As New Dictionary(Of String, Integer)()
d("new_var") = 100

Then, instead of finding the variable by its string name, you can just access the value of the item in the Dictionary by using it's key, like this:

Dim text As String = d("new_var")

The (Of String, Integer) part will probably be the part that confuses you. Those parameters specify the types for the key and the value of each item in the Dictionary . The first parameter is the type for the key, and the second one is the type for the value. So, in other words, you want the key for each item in the Dictionary (eg "new_var") to be a String , and you want the value of each item in the Dictionary (eg 100) to be an Integer . If you want to be able to store any kind of object, you could always declare it as Dictionary(Of String, Object) , but it's best to keep the type specified when you can. It's safer that way.

If you must use reflection, it would be better to first try and come up with a solution which uses attributes , if possible. But I doubt that you really need reflection at all, for what it sounds like you are trying to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM