如何在vb.net中动态将一个字符串类型的变量值传递给另一个变量名?

huangapple go评论61阅读模式
英文:

How to dynamically pass a variable (of string type) value to another variable name in vb.net?

问题

我曾是一名VFP程序员,对于VFP的一些强大技巧,比如动态声明一个变量并将其命名为另一个字符串变量,感到惊叹。我想知道如何在vb.net中实现相同的功能。我进行了搜索,但大多数解决方案都建议使用数组或列表,其中我无法使用变量的具体有意义的名称。

我有一张包含许多变量的表格,对于每个变量,我想要动态声明一个变量,其名称与变量名称相同,并将变量值赋给它。以下只是完整列表的5%:

如何在vb.net中动态将一个字符串类型的变量值传递给另一个变量名? 变量的部分列表

我可以一个一个声明所有的变量,但如果有更简洁的方法,我更愿意采用。

你能帮助我吗?

我还没有尝试任何方法。

英文:

I am a former VFP programmer and was amazed by some powerful technics of VFP such as declaring dynamically a variable and assign to it a name from another string variable. I am looking for how to do the same in vb.net. I search but most solutions suggest array or list where I could not use the specific meaningful name of the variables.

I have a list of many variables in a table and for each variable I would like to dynamically declare a variable that have the name of the variable and assign to to it the variable value. Below is just 5 % of the full list

如何在vb.net中动态将一个字符串类型的变量值传递给另一个变量名? partial list of the variables

I can declare all the variable one by one but I would prefer a shorter way if any.

How could you assist me?

I have not tried anything.

答案1

得分: 1

不能在强类型语言中动态创建变量。(你可以创建一个动态类型的变量,但这不是你要找的东西。)

看一下Dictionary类,它是一组键值对(名称和值),类似于经典的“哈希数组”或JavaScript中的对象。

编辑。当你在VB.Net中创建一个字典时,你需要指定键的数据类型(通常是字符串)和值的数据类型。如果所有的值都是整数,你可以像这样做:Dim myDict As New Dictionary(Of String, Integer)。如果你真的需要存储不同类的对象(使用同一个字典),你可以这样做:Dim myDict As New Dictionary(Of String, Object)(但你会失去类型安全性)。

英文:

You can't dynamically create variables in a strongly typed language. (You could create a dynamically typed variable, but that's not what you're looking for.)

Take a look at the Dictionary class, which is a collection of pairs (name and value), like a classic "hash array" or an object in JavaScript.

Edit. When you create a dictionary in VB.Net, you specify the datatype of the key (usually a String) and the datatype of the value. If all your values are Integers, yo do something like: Dim myDict As New Dictionary (Of String, Integer). If you really need to store different classes of objects (using the same dictionary), you may do: Dim myDict As New Dictionary (Of String, Object) (but you'll lose type safety).

huangapple
  • 本文由 发表于 2023年2月19日 18:49:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499582.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定