包含Spring.Net中的通用字典的通用字典

Ami*_*and 4 c# spring dictionary spring.net

我有一个包含属性的对象:

public Dictionary<string, Dictionary<string, List<ContextMenuItemModel>>> ContextMenuModel { get; set; }
Run Code Online (Sandbox Code Playgroud)

如何使用Spring.Net配置此属性?

Mar*_*ijn 6

好吧,在xml中配置这个并不漂亮,考虑切换到Spring.Net代码配置来配置C#中的spring上下文.

无论如何,要在xml中执行此操作,您将使用通用.net集合的构造函数.例如,List<T>采用IList<T>构造函数,因此您可以按如下方式配置字符串列表:

<object id="list1" type="System.Collections.Generic.List&lt;string>">
  <constructor-arg>
    <list element-type="string">
      <value>abc</value> 
      <value>def</value> 
    </list>
  </constructor-arg>
</object>
Run Code Online (Sandbox Code Playgroud)

请注意,在xml中你必须使用&lt;,因为使用<不是合法的xml.Spring.net文档中讨论了设置泛型集合值.

通用Dictionary<string, System.Collections.Generic.List<string>>可以以类似的方式配置,这也在本答案中讨论:

<object id="dic1" type="System.Collections.Generic.Dictionary&lt;string, System.Collections.Generic.List&lt;string>>">
  <constructor-arg>
    <dictionary key-type="string" value-type="System.Collections.Generic.List&lt;string>">
      <entry key="keyToList1" value-ref="list1" />
      <entry key="keyToList2" value-ref="list2" /> 
    </dictionary>
  </constructor-arg>
</object>
Run Code Online (Sandbox Code Playgroud)

你可能会看到下一个即将到来:

<object id="dic0" type="System.Collections.Generic.Dictionary&lt;string, System.Collections.Generic.Dictionary&lt;string, System.Collections.Generic.List&lt;string>>>">
  <constructor-arg>
    <dictionary key-type="string" value-type="System.Collections.Generic.Dictionary&lt;string, System.Collections.Generic.List&lt;string>>">
      <entry key="keyToDic1 " value-ref="dic1" />
    </dictionary>
  </constructor-arg>  
</object>
Run Code Online (Sandbox Code Playgroud)

哪个可以注射:

<object id="MyObject" type="MyNamespace.MyClass, MyAssembly">
  <property name="ContextMenuModel" ref="dic0" />
</object>
Run Code Online (Sandbox Code Playgroud)

这不是很漂亮,但您可以使用类型别名略微提高xml的可读性.