使用字符串作为变量名 [英] Using string as a name of a variable
问题描述
是否可以使用字符串作为变量名?例如..
我将 x 声明为私有双精度
Is it possible to use a string as a name of a variable? For Example..
I declared x as a private double
Private TextBox1Store,TextBox2Store,TextBox3Store As Double
我将使用它作为存储值的变量.
I will use that as a variables for storing value.
此函数将标签和文本框内的数字相乘并返回一个产品.
This function multiplies the number inside a label and textbox and returns a product.
Private Function mqtyCalc(ByVal y As Integer, ByVal z As Integer) As Integer
Dim w As Integer
w = y * z
Return w
End Function
这部分处理三个文本框事件.
This part handles three textbox events.
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged, TextBox3.TextChanged
Dim tb As TextBox = sender
Dim tempObjNm As String
tempObjNm = tb.Name + "Strore"
tempObjNm = mqtyCalc(someVariable.Text, Label1.Text)
End Sub
这就是我要解决的部分.
And this the part I'm trying to solve.
tempObjNm = someVariable.Name + "Strore"
tempObjNm = mqtyCalc(tb.Text, Label1.Text)
tempObjNm"在这个 sub 中被声明为字符串.
每次我在文本框内输入一个值时,这个 sub 将获取已插入值的文本框的名称,并且该名称将在其末尾添加Store"以模仿上面声明的变量名称.例如,
The "tempObjNm" is declared inside this sub as string.
Everytime I Input a value inside the textboxs, this sub will get the name of the textbox that has been inserted a value and the name will be added "Store" at their end Jus to mimic the variable name declared above. Example,
temObjNm = TextBox1Store(模仿私有 TextBox1Store)
temObjNm 当前是一个由
temObjNm = TextBox1Store (mimicking the Private TextBox1Store)
temObjNm is currently a string declared by
Dim tempObjNm As String
作为字符串
这部分是子的存储部分
tempObjNm = mqtyCalc(tb.Text, 4)
(注意 tempObjNm 的值 = "TextBox1Store"
(Take note that the value of tempObjNm = "TextBox1Store"
当我打印 TextBox1Store 时,它打印 0
When I print TextBox1Store, it prints 0
怎么样?难道不能使用字符串来模拟变量只是为了在其中存储值吗?
How is that? Is it not possible to use a string for mimicking the varible just to store value in it?
推荐答案
只需这样做:
Dim tb As TextBox = CType(sender, TextBox)
Me.Controls(tb.Name & "Store") = mqtyCalc(CInt(someVariable.Text), CInt(Label1.Text))
我强烈建议你做几件事.首先,在您的项目属性中启用 Option Strict On
,因为它将改进您的编程实践.而且,正如您在我的代码中所见,在 VB.NET 中使用 &
而不是 +
连接字符串.
I strongly suggest you a couple of things. First, enable Option Strict On
in you project properties, as it will improve your programming practices. And, as you can see in my code, concatenate strings with &
instead of +
in VB.NET.
这篇关于使用字符串作为变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!