2013-03-12 134 views
3

是否可以使用字符串作爲變量的名稱?例..
我聲明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

那是怎麼回事?是不是可以使用字符串來模仿變量來存儲值呢?

+0

'當我打印TextBox1Store時,它打印0'打印變量'TextBox1Store'時需要打印什麼? – 2013-03-12 10:00:01

+0

幫你一個忙,把** Option Strict On **放在你的代碼的頂部,或者進入你的VB首選項並將Option Strict設置爲On。 **將該項目設爲新項目的默認設置**。你有這行代碼:'mqtyCalc(someVariable.Text,Label1.Text)'。 '.Text'意味着那些是字符串,但你的'mqtyCalc'方法需要雙倍。這怎麼能編譯? – 2013-03-12 16:19:30

+0

Option Strict在我的項目屬性中爲On,而鍵入代碼並沒有得到任何錯誤。 – conquistador 2013-03-12 22:18:11

回答

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

發生錯誤「Propery'item''ReadOnly' – conquistador 2013-03-12 09:35:07

+1

哦,對不起,以爲你的'TextBox1Store'是控件。您不能從其字符串名稱(或其太複雜)訪問變量。但是,您可以使用此方法將值存儲在控件上,例如隱藏標籤。 – SysDragon 2013-03-12 09:44:10

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