简体   繁体   English

php $$ var等同于vb.net(vb2010)

[英]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. 我正在VB.NET中编写程序,我需要获取一个其字符串值是动态获取的变量。 Just like in PHP: 就像在PHP中一样:

$text = "new_var" (gotten dynamically)

$$text = 100

I want to do this in VB.NET. 我想在VB.NET中做到这一点。

The direct equivalent in VB.NET is called reflection . VB.NET中的直接等效项称为反射 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. 更好的解决方案可能是使用Dictionary对象。 The Dictionary class in .NET is an implementation of a hash-table which allows you to easily store key/value pairs. .NET中的Dictionary类是哈希表的实现,可让您轻松存储键/值对。 So, instead of storing the value in a variable, you could store it in a Dictionary , like this: 因此,您可以将其存储在Dictionary ,而不是将值存储在变量中,如下所示:

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: 然后,不用按其字符串名称查找变量,只需使用其键访问Dictionary中该项的值,如下所示:

Dim text As String = d("new_var")

The (Of String, Integer) part will probably be the part that confuses you. (Of String, Integer)部分可能会使您感到困惑。 Those parameters specify the types for the key and the value of each item in the Dictionary . 这些参数指定键的类型以及“ 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 . 因此,换句话说,您希望Dictionary每个项目的键(例如“ new_var”)为String ,并且希望Dictionary中每个项目的值(例如100)为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. 如果您希望能够存储任何类型的对象,则可以始终将其声明为Dictionary(Of String, Object) ,但是最好尽可能保留指定的类型。 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. 但是我怀疑您真的需要反思,因为听起来您正在尝试做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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