【发布时间】:2012-05-09 10:42:19
【问题描述】:
考虑以下代码:
Dim S1 As String = "a"
'this is the string in a file
Dim StringFromFile As String = "S1=hello"
Dim temp() As String = Split(StringFromFile, "=", -1, CompareMethod.Binary)
'temp(0) = variable name
'temp(1) = variable value
'my question is: how to assign value to S1?
我已经声明了一个名为 S1 的字符串。现在我想为 S1 分配新值。新的字符串值使用以下格式存储在文件中:[变量名][= 作为分隔符][字符串值]。检索存储在文件中的字符串变量名称和值后,如何将值分配给 S1?
注意:
temp(0) = "S1"
temp(1) = "hello"
需要注意的是,带有数据的字符串来自一个可能会不时变化的文件!当文件发生变化时,我希望变量也发生变化。
进一步说明
我需要一段代码,当处理像“S1=hello”这样的字符串时,代码会首先找到一个声明的变量(即S1),然后用“hello”字符串分配S1变量。 “=”只是作为变量名和变量值的分隔符。
更新:
我尝试使用 Mathias Lykkegaard Lorenzen 的 EDIT 2 示例,但在此行 "Field.SetValue(Me, VariableValue)" 上出现“NullReferenceException”失败。请帮我解决问题。以下是我基于 Mathias Lykkegaard Lorenzen 的 EDIT 2 示例的代码:
Public Sub Ask()
Try
Dim S1 As String = "a"
Dim StringFromFile As String = "S1=hello"
Dim temp() As String = Split(StringFromFile, "=", -1, CompareMethod.Binary)
'temp(0) = variable name
'temp(1) = variable value
'my question is: how to assign value to S1?
Dim TypeOfMe As Type = Me.GetType()
'did this for readability.
Dim VariableName As String = temp(0)
Dim VariableValue As String = temp(1)
'get the field in the class which is private, given the specific name (VariableName).
Dim Field As FieldInfo = TypeOfMe.GetField(VariableName, BindingFlags.NonPublic Or BindingFlags.Instance)
'set the value of that field, on the object "Me".
Field.SetValue(Me, VariableValue) '<-- this line caused NullReferenceException
MessageBox.Show(S1)
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
【问题讨论】:
-
您通常不会这样做,即使在支持这种类型的语言中也是如此。您保留键值对的哈希表/字典,而不是普通变量。
-
@PanPizza 检查我的答案 - 我刚刚编辑了它。
-
好的,刚刚注意到您想根据变量的名称动态分配变量。对此也有解决方案,我刚刚再次修改了我的问题以反映这一点。
-
Pan Pizza 请使用 StringBuilder 而不是使用 Strings。
-
我也认为哈希表、字典或其他键=值对类型的数据结构是处理这些数据的更好方法。
标签: .net vb.net string variable-assignment