How to set values on attributes in a structure with reflection

G

Gunnar

Hi,

I've struggled with this problem for a while now without finding a
solution.
The scenario is as follows:

- I have a flat text file exported from a main frame.
- I use a structure to map data to the data in the file:
Public Structure PartRecord
<VBFixedString(8)> Public PartID As String
<VBFixedString(10)> Public Part As String
End Structure

- Now I want to use Reflection to bind data from the
text file to the structure. Vbfixedstring attribute are used to
determine the record structure in the text file:

Dim obj As PartRecord
dim recordType As Type
obj = Activator.CreateInstance(recordType)

recordType.InvokeMember("PartID", BindingFlags.SetField, Nothing, obj,
New Object() {"12345678"})

- The problem is that no value is set.
What am I doing wrong?
Can't members of a Structure be invoked?

Appreciate all help that can lead me to a solution of this.


Best regards

Gazza
 
M

Mattias Sjögren

- The problem is that no value is set.
What am I doing wrong?

You're modifying a boxed copy of the structure. Try it like this

Dim tmp As ValueType = obj
recordType.InvokeMember(..., tmp, ...)
obj = DirectCast(tmp, PartRecord)



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top