.GetType().GetProperties()以不同的顺序返回属性 [英] .GetType().GetProperties() returns properties in different order

查看:75
本文介绍了.GetType().GetProperties()以不同的顺序返回属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查我们的配置文件,看看它是否与我要创建一个新的配置文件相同.此方法称为GetConfig().

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().

几个小时后,我注意到如果我保存配置文件,然后调用GetConfig,它会起作用,但是如果我关闭程序,请启动它并加载我的配置文件,然后调用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.

在下面您可以看到我的意思,属性 b 是类的对象.有3个以上的属性,但我只想举一个小例子:

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

下一个配置对象

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

第二个对象

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);

非常感谢您的帮助.

推荐答案

您不能对 Type.GetProperties 的返回值的顺序进行任何假设,请参见

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

GetProperties方法不返回特定属性顺序,例如字母顺序或声明顺序.您的代码不得取决于返回属性的顺序,因为顺序会有所不同.

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.

这篇关于.GetType().GetProperties()以不同的顺序返回属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆