.GetType().GetProperties() returns properties in different order

眉间皱痕 提交于 2019-11-30 09:47:21

问题


I want to check our configuration file and see if it is the same as if I were to create a new configuration file. This method is called GetConfig().

After some hours I noticed that if I save my configuration file and then call GetConfig it works, but if I close the program start it up and load my configuration file in and call GetConfig() it returns my properties in a different order.

Below you can see what I mean, property b is an object of a class. There are more than 3 properties, but I only wanted to give a small example:

- - - - - - - - -- - - - - - --   S A V E   C O N F I G
 - - - - - - -- -   G E T   C O N F I G
1 Field: a
1 Field: b
1 Field: c

and the next config object it has to save.

1 Field: a
1 Field: b
1 Field: c

When I load the config on the same instance

 - - - -- - - - - - - - - -- -  A R E   E Q U A L
 - - - - - - -- -   G E T   C O N F I G
1 Field: a
1 Field: b
1 Field: c

next config object

1 Field: a
1 Field: b
1 Field: c

However when I load my config when I restart the program I get this:

- - - -- - - - - - - - - -- -  A R E   E Q U A L
 - - - - - - -- -   G E T   C O N F I G
1 Field: a
1 Field: b   <-- correct
1 Field: c

2nd object

1 Field: a
1 Field: c
1 Field: b   <-- should be 2nd.

So when I try to compare both configuration files they do not match. Has anybody any experience with this?

foreach (var field in channel.GetType().GetProperties())
                    {
                        Console.WriteLine(channel.ChannelNumber + " Field: " + field.Name);

Help is much appreciated.


回答1:


You cannot make any assumption about the order of return values of Type.GetProperties, see what documentation says:

The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which properties are returned, because that order varies.

If you want an specific order, you should make your code order the collection returned.



来源:https://stackoverflow.com/questions/33365036/gettype-getproperties-returns-properties-in-different-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!