busarider29 busarider29 - 4 months ago 13
Vb.net Question

Is there a way to iterate through a Structure's properties?

I have a Data Structure that has a 29 boolean data types in it. Is there a way to iterate through the Struct's properties in a For loop without exlicitly stating each property name in normal property syntax.

This is what I started with but this won't work.

Public Structure ST_PLCStruct_Bools
Public testTypeNS As Boolean '1 byte
Public testTypeOR As Boolean '1 byte
Public torqueTypeBreak As Boolean '1 byte
Public torqueTypeFix As Boolean '1 byte
Public sheaveHigh As Boolean '1 byte
Public sheaveLow As Boolean '1 byte
Public directionCW As Boolean '1 byte
Public directionCCW As Boolean '1 byte
Public cycleStart As Boolean '1 byte
Public cycleStarted As Boolean '1 byte
Public cycleStop As Boolean '1 byte
Public cycleStopped As Boolean '1 byte
Public pneuActuateAuto As Boolean '1 byte
Public pneuActuateMan As Boolean '1 byte
End Structure

Private plcData_Bools As ST_PLCStruct_Bools

For i = 0 To 28
plcData_Bools(i) = binaryReader.ReadBoolean
Next


Thanks.

Answer

Using reflection, you can use FieldInfo.SetValue to set the values without coding the name of each field. Using a structure vs. a class complicates things a little due to boxing of value types:

Private plcData_Bools As ST_PLCStruct_Bools

Dim boxed As ValueType = plcData_Bools
For Each f In GetType(ST_PLCStruct_Bools).GetFields()
    f.SetValue(boxed, binaryReader.ReadBoolean())
Next
plcData_Bools = DirectCast(boxed, ST_PLCStruct_Bools)
Comments