您的位置:知识库 » 软件测试

[Spring.NET IoC] 之五:列表参数

作者: Q.yuhen  来源: Q.yuhen  发布时间: 2008-12-25 23:16  阅读: 4635 次  推荐: 1   原文链接   [收藏]  

我们可以在配置文件中向构造方法或者属性注入列表型参数,诸如 Array、ArrayList、Hashtable 等。

1. IList

在 .NET Framework 中实现 IList 的主要是 Array、ArrayList。

<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.springframework.net
         http://www.springframework.net/xsd/spring-objects.xsd">

  <object id="HelloWorld" type="ConsoleApplication1.SpringNet.HelloWorld, Learn.CUI">
    <constructor-arg name="list">
      <list>
        <value>1</value>
        <value>2</value>
        <value>3</value>
        <value>4</value>
      </list>
    </constructor-arg>
  </object>
</objects>
public class HelloWorld
{
  public HelloWorld(IList list)
  {
    Console.WriteLine(list); // output: ArrayList
    foreach (object o in list)
      Console.WriteLine(o);
  }
}


我们会发现 Spring.NET IoC 缺省使用 ArrayList 来实现 IList 列表参数。

2. IDictionary

实现 IDictionary 的最常用类型是 Hashtable。

<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.springframework.net
         http://www.springframework.net/xsd/spring-objects.xsd">

  <object id="HelloWorld" type="ConsoleApplication1.SpringNet.HelloWorld, Learn.CUI">
    <constructor-arg name="dict">
      <dictionary>
        <entry key="1" value="a" />
        <entry key="2" value="b" />
        <entry key="3" value="c" />
        <entry key="4" value="d" />
      </dictionary>
    </constructor-arg>
  </object>
</objects>
public class HelloWorld
{
  public HelloWorld(IDictionary dict)
  {
    Console.WriteLine(dict); // output:System.Collections.Specialized.HybridDictionary
    foreach (object o in dict.Keys)
    {
      Console.WriteLine("{0}={1}", o, dict[o]);
    }
  }
}


看看 System.Collections.Specialized.HybridDictionary 的MSDN说明

在集合较小时,使用 ListDictionary 来实现 IDictionary,然后当集合变大时,切换到 Hashtable。
建议将该类用于字典中的元素数量未知的情况。它利用了 ListDictionary 处理小集合时性能改善的优点,同时也可灵活地切换到处理较大集合时能力比 ListDictionary 更好的 Hashtable。
如果集合的初始大小大于 ListDictionary 的最佳大小,那么集合立即存储在 Hashtable 中,以避免将元素从 ListDictionary 复制到 Hashtable 产生的系统开销。


不错,考虑得很周详。

1
0

软件测试热门文章

    软件测试最新文章

      最新新闻

        热门新闻