【问题标题】:Add entry to dictionary in child object在子对象的字典中添加条目
【发布时间】:2013-09-09 04:17:15
【问题描述】:

如何从子对象添加条目到在父对象中定义的字典?

*更新 我编辑我的配置如下:

<object id="ParentType" singleton="false" type="SomeType">
  <property name="FieldNameMap">
   <dictionary key-type="string"  value-type="string" >
     <entry key="Title" value="TitleName"/>     
    </dictionary>
  </property>
</object>

<object id="ChildType" singleton="false" type="SomeType" parent="ParentType">
  <property name="FieldNameMap">
   <dictionary merge="true">
     <!-- this entry should be added to, not replace the whole Dictionary -->
     <entry key="Position" value="PositionName"/>     
    </dictionary>
  </property>
</object>

但是,不幸的是,它现在抛出异常:

无法转换类型的属性值 [System.Collections.Specialized.HybridDictionary] 到所需类型 [System.Collections.Generic.IDictionary`2[[System.String, ],[System.String,mscorlib,版本=4.0.0.0,文化=中性, PublicKeyToken=b77a5c561934e089]]

【问题讨论】:

  • 我尝试在子字典中指定key-typevalue-type,结果相同

标签: spring configuration configuration-files spring.net


【解决方案1】:

我自己没有尝试过,但是according to the docs,如果集合本身暴露为只读属性,spring.net 将使用集合的Add 方法添加项目。

因此可以使用object definition inheritance 来实现您描述的行为。配置将类似于:

<object id="ParentType" singleton="false" type="SomeType"
        abstract="true">
  <property name="FieldNameMap">
   <dictionary>
     <entry key="Title" value="TitleName"/>     
    </dictionary>
  </property>
</object>

<object id="ChildType" singleton="false" type="SomeType" 
        parent="ParentType">
  <property name="FieldNameMap">
   <dictionary>
     <!-- this entry should be added to, not replace the whole Dictionary -->
     <entry key="Position" value="PositionName"/>     
    </dictionary>
  </property>
</object>

这仅在 FieldNameMap 是只读属性时才有效。

【讨论】:

  • 正确,甚至更好(使用 Spring 1.3+):您现在可以合并非只读列表、字典、名称值和集合集合(参见 5.3.2.6. 集合合并)。
  • 问题是,它没有按预期工作,请查看更新的 Q
  • 修复问题,创建拉取请求:github.com/spring-projects/spring-net/pull/52
  • 您问题中的子对象定义没有引用父对象;你试过&lt;object id="ChildType" singleton="false" type="SomeType" ___ parent="ParentType" ___ &gt;
  • 抱歉,这是 Q 中的一个错字。已更正。
猜你喜欢
  • 2020-05-04
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
  • 2016-02-03
  • 2016-08-14
  • 2011-02-07
  • 2017-02-09
  • 2020-12-01
相关资源
最近更新 更多