Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
825 views
in Technique[技术] by (71.8m points)

c# - .GetType().GetProperties() returns properties in different order

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...