如何使用 VB.NET 為字元串賦值?
考慮以下程式碼:
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 分配新值。新的字元串值使用以下格式儲存在文件中:$$ variable name $$$$ = as separator $$$$ string value $$. 檢索儲存在文件中的字元串變數名稱和值後,如何將值分配給 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
您可以使用反射來設置 S1 值:
Imports System.Reflection Public Class Form1 Public S1 As String = "a" Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click Dim StringFromFile As String = "S1=hello" Dim temp() As String = Split(StringFromFile, "=", -1, CompareMethod.Binary) 'temp(0) = variable name 'temp(1) = variable value SetS1(Me, "S1", temp(1)) MessageBox.Show(S1) End Sub ''' <summary> ''' ''' </summary> ''' <param name="obj">the class that stores your S1 public field</param> ''' <param name="fieldName">that is your S1 field</param> ''' <param name="Value">S1 new value, that is hello</param> ''' <remarks></remarks> Public Sub SetS1(ByVal obj As Object, ByVal fieldName As String, ByVal Value As Object) Try Dim fi As FieldInfo = obj.GetType().GetField(fieldName, BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic) If Not fi Is Nothing Then fi.SetValue(obj, Value) End If Catch ex As Exception End Try End Sub End Class額外資源
有一本關於反射的書非常好,看看:
反射是 .NET 提供的一種機制,使開發人員能夠使他們的程序更加靈活和動態。反射使應用程序變得更加模組化、可擴展和可配置成為可能。基於物件導向和 .NET 類型系統的基礎,反射提供了在執行時動態檢查、修改甚至創建對象的機制。.NET 還增加了程序員向其類型添加屬性的能力,這些屬性提供有關類型的元數據,可以在執行時通過反射檢查和使用這些元數據。
本書探討了反射的所有使用方式,並確定了依賴反射實現其功能的實際應用程序和重要的程式技術。它涵蓋了反射 API、.NET 中屬性的使用,還介紹了 .NET 為動態生成程式碼提供的機制——所有這些技術都允許開發人員建構更靈活、更動態的應用程序。