TC code
TC code

Reputation: 21

iterator nested struct in c#

Lets say we have a struct

public struct a{
  public struct b;
  public struct c;
   .
   .
   .
  public struct n;
}

public struct b{
 public int b1 = 1;
 public int b2 = 2;
}

I want to print all member of struct such as

struct a

struct b

b1=1 b2=2

.

.

.

struct n

member

I already reference this link

but it use field , I don't know how to access nested struct by field .

Upvotes: 0

Views: 141

Answers (2)

E. Shcherbo
E. Shcherbo

Reputation: 1148

It can be implemented recursively:

    void PrintMembers(Type type, object o)
    {
        Console.WriteLine(type.Name);

        foreach (var field in type.GetFields(BindingFlags.Instance |
                                                         BindingFlags.NonPublic |
                                                         BindingFlags.Public))
        {
            object value = field.GetValue(o);
            if (field.FieldType.IsPrimitive)
            {
                Console.WriteLine("{0} = {1}", field.Name, value);
            }
            else
            {
                PrintMembers(value.GetType(), value);
            }
        }
    }

Then call it like

 var myStruct = new a();

 PrintMembers(typeof(a), myStruct);

Keep in mind this call requires boxing of myStruct object.

Upvotes: 1

Jamiec
Jamiec

Reputation: 136074

Notwithstanding the syntax errors in your code, for listing the public members of a you would use typeof(a).GetMembers(BindingFlags.Public) and for listing the fields of b it would be typeof(b).GetFields().

var aType = typeof(a);
foreach(var member in aType.GetMembers(BindingFlags.Public))
    Console.WriteLine(member.Name);

var bType = typeof(b);
foreach(var field in bType.GetFields())
    Console.WriteLine(field.Name);

Live example: https://dotnetfiddle.net/BBG6wa

Upvotes: 1

Related Questions