where is my reflection mistake

kavehyn

New member
Joined
Jun 4, 2008
Messages
2
Programming Experience
5-10
hi all
code below is belong to a procedure , its goal is to receve a dataset and a structure and then copy the dataset's fields into structure's same fieilds .
fields name and Fields datattype in dataset and structure are similar

problem is that
f.SetValue(MyObject, NewAmount)
dont work atall, (Amount) variable is present but it dont place inside
MyObject ,
please help me to correct the error

ds : the dataset
Stru_Employee : the structure that should be initialize


Dim ItemCounter As Integer
ItemCounter = 0
Dim MyObject As New Stru_Employee

For Each f As System.Reflection.FieldInfo In GetType (Stru_Employee).GetFields
Dim Amount = ds.Tables(0).Rows(0).Item(ItemCounter)


f.SetValue(MyObject, Amount)
ItemCounter = ItemCounter + 1
Next
 
obj parameter of SetValue method is ByVal and Object type, so your value type structure variable is not used, instead a copy is passed to it and changed and lost when SetValue finishes. A workaround is to assign it the value to a ValueType variable, and pass this to SetValue. ValueType is the base class for all value types, since this is a class a reference is created that is correctly returned modified from SetValue. See example:
VB.NET:
Structure A
    Public x, y, z As Integer
End Structure

Sub initializeA()
    Dim o As ValueType = New A
    For Each f As Reflection.FieldInfo In GetType(A).GetFields
        f.SetValue(o, 1)
    Next
    Dim one As A = DirectCast(o, A)
End Sub
 

Latest posts

Back
Top