How can I get MemberInfos of a class in the order the members are declared?

107 Views Asked by At

Let's say I have the following class:

public class Target
{
   public int field1;
   public int field2;
   public int Prop1 { get; set; }
   public int Prop2 { get; set; }
}

If I do a:

foreach(far f in typeof(Target).GetFields())
   Console.WriteLine(f.Name);

I would get the fields in the order they're declared in (field1 then field2). Same thing if I did GetProperties

Now, consider the following:

public class Target
{
   public int field1;
   public int Prop1 { get; set; }
   public int field2;
   public int Prop2 { get; set; }
}

When I did:

    var members = typeof(Target).GetMembers()
                 .Where(m => m.MemberType == MemberTypes.Field ||
                             m.MemberType == MemberTypes.Property);

    foreach (var m in members)
        Console.WriteLine(m.Name);

I got the following output:

Prop1
Prop2
field1
field2

Obviously, not in the order the members are declared in (which is field1, Prop1, field2 and Prop2)

Is there any way I can get the members in that order?

Thanks.

EDIT:

I care about the order, because I work with Unity3D (Game engine) and I'm writing a custom editor for a certain type. The type will have fields and properties, I want to draw the fields/properties in the order that they're declared in. Of course, unity does draw the fields in the order they're declared in, but it doesn't draw properties. That's why I'm making my own drawers/editors to support property drawing.

enter image description here

0

There are 0 best solutions below