VB.NET Iterating through objects of a structure

2019-05-10 11:12发布

问题:

I have a structure "xyz" with 3 string objects in it. "foo" "bar" and "abc" I want to iterate through the structure and compare the names of the objects.

Structure xyz
    dim foo as string
    dim bar as string
    dim abc as string
End Structure

Pseudo:

For each x as object in xyz 
    if x.Name = "foo" then
        'bang
    end if
End each

Is this possible?

回答1:

If this is just a one time thing you're probably going to have an easier time using a Dictionary instead, but you could do this with Reflection if you prefer to keep the structure.

This little code snippet will list out each structure member for you in a StringBuilder.

Dim sbOutput As New System.Text.StringBuilder
Dim t As Type = GetType(xyz)
For Each p As System.Reflection.FieldInfo In t.GetFields()
  sbOutput.AppendLine(p.Name)
Next