I am using the code in https://stackoverflow.com/a/531388/528131 to successfully retrieve all the properties of an object instance from a base, the problem being that the derived type's properties are being iterated over first. Due to the nature of the protocol, i need the base properties first.
x |
y | B
z |
w | A
B and A are classes, B derives from A. x, y, z are properties from B and w is a property from A
This is a scheme of how A.GetProperties(); is returning. I need this instead:
w | A
x |
y | B
z |
Is there any way to get the fields in that order EXACTLY?
The fields in a type are not "ordered". The ordering of the items in those methods is an implementation detail and relying on them is strongly discouraged.
You should order the items yourself, with the expectation that they could start at any position, to ensure your program is robust instead of fragile.
Since each property can be asked for the type that declares it you can create a lookup at the start that gives a number to each class in the hierarchy from the type you start with all the way up to object
by walking the BaseType
property of Type
and order by the lookup value of the declaring type of each property:
public static IEnumerable<PropertyInfo> GetOrderedProperties(Type type)
{
Dictionary<Type, int> lookup = new Dictionary<Type, int>();
int count = 0;
lookup[type] = count++;
Type parent = type.BaseType;
while (parent != null)
{
lookup[parent] = count;
count++;
parent = parent.BaseType;
}
return type.GetProperties()
.OrderByDescending(prop => lookup[prop.DeclaringType]);
}