Hi,
I wants to use System.Reflection.FieldInfo.SetValue() to set the value of a "Field" of in a "Structure", I fails. Following is the code I modify from the Example of System.Reflection.FieldInfo.SetValue() from MSDN (The underlined word is what I have changed).
My question is how set the value of a "Field" of a "Structure" by giving the name of the "Field" in a string variable
Imports System Imports System.Reflection Imports System.Globalization
Public Structure Example Private myString As String Public Sub New(pValue as string) myString = pValue End Sub ReadOnly Property StringProperty() As String Get Return myString End Get End Property End Structure
Public Module FieldInfo_SetValue Sub Main()
Dim myObject As New Example("Old Value") Dim myType As Type = GetType(Example) Dim myFieldInfo As FieldInfo = myType.GetField("myString", _ BindingFlags.NonPublic Or BindingFlags.Instance)
' Display the string before applying SetValue to the field. Console.WriteLine(vbCrLf & "The field value of myString is ""{0}"".", _ myFieldInfo.GetValue(myObject)) ' Display the SetValue signature used to set the value of a field. Console.WriteLine("Applying SetValue(Object, Object).")
' Change the field value using the SetValue method. myFieldInfo.SetValue(myObject, "New value") ' Display the string after applying SetValue to the field. Console.WriteLine("The field value of mystring is ""{0}"".", _ myFieldInfo.GetValue(myObject))
End Sub End Module
.NET Development8
|