开发者

Spring.net inject dictionary order question?

开发者 https://www.devze.com 2023-04-04 02:55 出处:网络
I use spring.net inject a开发者_StackOverflow社区 Dictionary<string,string> in this order:

I use spring.net inject a开发者_StackOverflow社区 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号