考虑以下代码:
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 示例,但在此行上出现“NullReferenceException”失败"Field.SetValue(Me, VariableValue)"
。请帮我解决问题。以下是我基于 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