使用字符串作为变量的名称
是否可以使用字符串作为变量的名称?例..
我声明x作为私人双使用字符串作为变量的名称
Private TextBox1Store,TextBox2Store,TextBox3Store As Double
我将使用作为存储值的变量。
此函数将标签和文本框内的数字相乘并返回一个产品。
Private Function mqtyCalc(ByVal y As Integer, ByVal z As Integer) As Integer
Dim w As Integer
w = y * z
Return w
End Function
这部分处理三个文本框事件。
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
而这正是我试图解决的部分。
tempObjNm = someVariable.Name + "Strore"
tempObjNm = mqtyCalc(tb.Text, Label1.Text)
“tempObjNm”在此子内部作为字符串声明。
每次我在文本框内输入一个值时,这个子文件将获得已经插入一个值的文本框的名称,并且该名称将在其末尾添加“存储”以模拟上面声明的变量名称。例如,
temObjNm = TextBox1Store(模仿私人TextBox1Store)
temObjNm是目前由
Dim tempObjNm As String
声明为字符串
这一部分是子的存储部分的字符串
tempObjNm = mqtyCalc(tb.Text, 4)
(请注意tempObjNm的值=“TextBox1Store”
当我打印TextBox1Store时,它打印0
那是怎么回事?是不是可以使用字符串来模仿变量来存储值呢?
只是这样做:
Dim tb As TextBox = CType(sender, TextBox)
Me.Controls(tb.Name & "Store") = mqtyCalc(CInt(someVariable.Text), CInt(Label1.Text))
我强烈建议你几件事情。首先,在您的项目属性中启用Option Strict On
,因为它会改进您的编程实践。而且,正如你在我的代码中看到的,在VB.NET中连接字符串&
而不是+
。
发生错误“Propery'item''ReadOnly' – conquistador 2013-03-12 09:35:07
哦,对不起,以为你的'TextBox1Store'是控件。您不能从其字符串名称(或其太复杂)访问变量。但是,您可以使用此方法将值存储在控件上,例如隐藏标签。 – SysDragon 2013-03-12 09:44:10
您能使用一个Dictionary(Of String, Double)
吗?
Private values As New Dictionary(Of String, Double)
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
setValue(sender)
End Sub
Private Sub setValue(sender As Object)
Dim tb As TextBox = CType(sender, TextBox)
Dim tbName As String = tb.Name & "Strore"
If Not values.ContainsKey(tbName) Then
values.Add(tbName, tb.Text)
Else
values(tbName) = tb.Text
End If
End Sub
Private Function getValue(sender As Object) As Double
Dim tbName As String = CType(sender, TextBox).Name & "Strore"
If Not values.ContainsKey(tbName) Then
Return Double.NaN
Else
Return values(tbName)
End If
End Function
'当我打印TextBox1Store时,它打印0'打印变量'TextBox1Store'时需要打印什么? – 2013-03-12 10:00:01
帮你一个忙,把** Option Strict On **放在你的代码的顶部,或者进入你的VB首选项并将Option Strict设置为On。 **将该项目设为新项目的默认设置**。你有这行代码:'mqtyCalc(someVariable.Text,Label1.Text)'。 '.Text'意味着那些是字符串,但你的'mqtyCalc'方法需要双倍。这怎么能编译? – 2013-03-12 16:19:30
Option Strict在我的项目属性中为On,而键入代码并没有得到任何错误。 – conquistador 2013-03-12 22:18:11