.GetType().GetProperties() returns properties in d

2019-01-28 23:34发布

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条回答
Lonely孤独者°
2楼-- · 2019-01-28 23:53

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.

查看更多
登录 后发表回答