Why System.Reflection.FieldInfo.SetValue() works for "Class" but not "Structure"?  
Author Message
Johnson Cheung





PostPosted: .NET Base Class Library, Why System.Reflection.FieldInfo.SetValue() works for "Class" but not "Structure"? Top

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  
 
 
nobugz





PostPosted: .NET Base Class Library, Why System.Reflection.FieldInfo.SetValue() works for "Class" but not "Structure"? Top

The code works fine if you declare Example as a Class instead of a Structure. The problem here is that your Example structure is a value type. SetValue() requires an object type.


 
 
urania





PostPosted: .NET Base Class Library, Why System.Reflection.FieldInfo.SetValue() works for "Class" but not "Structure"? Top

try using:

ExStruct myStruct = new ExStruct;

Type myType = myStruct.GetType();

FieldInfo myField = myType.GetField("FieldName");

Fielddata = myField.GetValue(myStruct);