是否可以使用字符串作为变量的名称?例如..
我将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”在此子句内声明为字符串 每次我在文本框中输入一个值时,此子将获得已插入值的文本框的名称,名称将在其末尾Jus添加“Store”以模仿上面声明的变量名称。例如,
temObjNm = TextBox1Store(模仿私有TextBox1Store)
temObjNm当前是由
Dim tempObjNm As String
作为字符串
这部分是子
的存储部分 tempObjNm = mqtyCalc(tb.Text, 4)
(请注意tempObjNm =“TextBox1Store”的值
当我打印TextBox1Store时,它会打印0
那是怎么回事?是不是可以使用字符串来模仿varible只是为了在其中存储值?答案 0 :(得分:2)
这样做:
Dim tb As TextBox = CType(sender, TextBox)
Me.Controls(tb.Name & "Store") = mqtyCalc(CInt(someVariable.Text), CInt(Label1.Text))
我强烈建议你做几件事。首先,在项目属性中启用Option Strict On
,因为它将改进您的编程实践。而且,正如您在我的代码中看到的那样,在VB.NET中用&
而不是+
连接字符串。
答案 1 :(得分:1)
您可以使用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
答案 2 :(得分:0)
我想分享我正在使用的代码。希望这对以后的读者有帮助。
Dim tb As TextBox = sender
Dim tempObjNm As String
tempObjNm = tb.Name + "Strore"
Me.GetType.GetField(tempObjNm).SetValue(Me, CType(mqtyCalc(someVariable.Text, Label1.Text), Double))