Spring.net inject dictionary order question?

ε祈祈猫儿з 提交于 2019-12-11 02:19:33

问题


I use spring.net inject a Dictionary<string,string> in this order:

<object id="dictLang" type="System.Collections.Generic.Dictionary&lt;string,string&gt;">
  <constructor-arg>
    <dictionary key-type="string" value-type="string" merge="0">
      <entry key="zh-CN" value="中文" />
      <entry key="en-US" value="英文" />
      <entry key="th-TH" value="泰文" />
    </dictionary>
  </constructor-arg>
</object>

When I use foreach to iterate it, it outputs this:

code=en-US,name=英文
code=th-TH,name=泰文
code=zh-CN,name=中文

I found it is ordered by the key, how can I keep the order as I injected it?

When I create a dictionary manually:

Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("zh-CN", "中文");
            dic.Add("en-US", "英文");
            dic.Add("th-TH", "泰文");

It is the same order when I iterate it, that's weird!

I thought about using OrderedDictionary, but I don't know how to inject.


回答1:


Any "ordering" of Generic.Dictionary<K,V> is by pfm and cannot be relied upon -- the fact that spring.net's injection leads to a slightly different key iteration order (perhaps one that seems to be sorted) is just luck and cannot be relied upon.

Notice that the injected dictionary was passed an IDictionary itself as the constructor argument making it not identical to the manual code. Compare it with:

Dictionary<string, string> temp = new Dictionary<string, string>();
temp.Add("zh-CN", "中文");
temp.Add("en-US", "英文");
temp.Add("th-TH", "泰文");
Dictionary<string, string> dic = new Dictionary<string, string>(temp);

Even if the above doesn't yield the same key iteration order as that of spring.net, it is possible that there are other factors at play, such as a different default capacity for "temp".

I cannot answer the "OrderedDictionary" part, however. (Most of the "specialized" collections are very underwhelming.)

Happy coding.



来源:https://stackoverflow.com/questions/7370823/spring-net-inject-dictionary-order-question

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