对象属性的排序

本文关键字:排序 属性 对象 | 更新日期: 2023-09-27 18:35:13

private string DoStuff(object result, StringBuilder returnBuilder)
{
    // get a list of all public properties and order by name 
    // so we can guarentee that the order of the headers and 
    // the results are the same
    foreach (var prop in result.GetType().GetProperties().OrderBy(x => x.Name))
    {
        //    do something cool
    }
}

我的问题是,如果没有 for 循环中的OrderBy,我是否可以保证列表的本机顺序将是属性在对象中声明的顺序

对象属性的排序

来自 MSDN:

方法不返回特定属性 顺序,例如按字母顺序或声明顺序。您的代码不得 取决于返回属性的顺序,因为 顺序各不相同。