C#反射属性顺序

Mac*_*ius 3 c# reflection

我使用/sf/answers/37197191/中的代码从基础成功检索对象实例的所有属性,问题是派生类型的属性首先被迭代.由于协议的性质,我首先需要基本属性.

x |
y | B
z |
w | A
Run Code Online (Sandbox Code Playgroud)

B和A是类,B来自A. x,y,z是来自B的属性,w是来自A的属性

这是A.GetProperties(); 正在回归 我需要这个:

w | A
x |
y | B
z |
Run Code Online (Sandbox Code Playgroud)

有没有办法按顺序获得字段?

Ser*_*rvy 16

类型中的字段不是"有序"的.这些方法中项目的排序是一个实现细节,强烈建议不要依赖它们.

你应该自己订购这些物品,期望它们可以从任何位置开始,以确保你的程序健壮而不是脆弱.

由于可以要求每个属性声明它的类型,您可以在开始时创建一个查找,它为层次结构中的每个类提供一个数字,从您开始的类型一直到object步行BaseType属性Type和按顺序排序查找每个属性的声明类型的值:

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]);
}
Run Code Online (Sandbox Code Playgroud)