Spring.net注入字典顺序问题? [英] Spring.net inject dictionary order question?
问题描述
我使用spring.net以此顺序注入字典< string,string>
I use spring.net inject a Dictionary<string,string>
in this order:
<object id="dictLang" type="System.Collections.Generic.Dictionary<string,string>">
<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>
当我使用foreach来迭代它,它会输出:
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?
手动创建字典时:
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!
我曾考虑过使用 OrderedDictionary
,但我不知道如何注入。
I thought about using OrderedDictionary
, but I don't know how to inject.
推荐答案
Generic.Dictionary< K,V>
是由 pfm ,不能依赖 - spring.net的注入导致一个稍微不同的键迭代顺序(也许一个似乎要排序)只是运气,不能依赖。
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.
请注意,注入的字典作为构造函数参数传递了一个IDictionary本身,使其与手动代码不同。比较:
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);
即使上述不能产生与spring.net相同的密钥迭代顺序,它有可能还有其他因素,例如不同的默认容量 fortemp。
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".
然而,我无法回答OrderedDictionary部分。 (大多数专业系列都是非常压倒性的。)
I cannot answer the "OrderedDictionary" part, however. (Most of the "specialized" collections are very underwhelming.)
快乐编码。
这篇关于Spring.net注入字典顺序问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!