在VB.NET中动态创建变量 [英] Dynamically create variables in VB.NET

查看:153
本文介绍了在VB.NET中动态创建变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图弄清楚一段时间,似乎无法找出答案。我不明白为什么这是不可能的。我在VB.NET中编码。

I have been trying to figure this out for some time now and can't seem to figure out an answer to it. I don't see why this would be impossible. I am coding in VB.NET.

这是我的问题:
我需要动态创建变量并能够引用他们后来在代码中。

Here is my problem: I need to dynamically create variables and be able to reference them later on in the code.

更多详细信息:
变量的数量来自对用户定义值的一些数学运算。在这种具体情况下,我想创建整数,尽管我预见到需要使用任何类型的变量来实现这一点。看来我最大的问题是能够以独一无二的方式命名,以便稍后再引用它们。

More Details: The number of variables comes from some math run against user defined values. In this specific case I would like to just create integers, although I foresee down the road needing to be able to do this with any type of variable. It seems that my biggest problem is being able to name them in a unique way so that I would be able to reference them later on.

简单示例: / strong>
假设我有一个值为10,其中我需要做变量。我想运行一个循环来创建这10个整数。后来在代码中,我将引用这10个整数。

Simple Example: Let's say I have a value of 10, of which I need to make variables for. I would like to run a loop to create these 10 integers. Later on in the code I will be referencing these 10 integers.

对我来说似乎很简单,但我无法理解。任何帮助将不胜感激。感谢提前。

It seems simple to me, and yet I can't figure it out. Any help would be greatly appreciated. Thanks in advance.

推荐答案

最好的方式来做这样的事情是用 Dictionary(T) 类。它是通用的,因此您可以使用它来存储任何类型的对象。它允许您轻松存储和检索代码/值对。在你的情况下,key将是变量名,value将是变量值。所以例如:

The best way to do something like this is with the Dictionary(T) class. It is generic, so you can use it to store any type of objects. It allows you to easily store and retrieve code/value pairs. In your case, the "key" would be the variable name and the "value" would be the variable value. So for instance:

Dim variables As New Dictionary(Of String, Integer)()
variables("MyDynamicVariable") = 10  ' Set the value of the "variable"
Dim value As Integer = variables("MyDynamicVariable")  ' Retrieve the value of the variable

这篇关于在VB.NET中动态创建变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆