Spring.NET依赖注入框架学习-- 泛型对象的创建和使用

Spring.NET依赖注入框架学习-- 泛型对象的创建和使用

泛型对象的创建方法和普通对象是一样的。

通过构造器创建泛型对象

下面是一个泛型类的代码:

 1 namespace GenericsPlay
 2 {
 3     public class FilterableList<T>
 4     {
 5         private List<T> list;
 6         
 7         private String name;
 8 
 9         public List<T> Contents
10         {
11             get { return list; }
12             set { list = value; }
13         }
14 
15         public String Name
16         {
17             get { return name; }
18             set { name = value; }
19         }
20         
21         public List<T> ApplyFilter(string filterExpression)
22         {
23             /// should really apply filter to list ;)
24             return new List<T>();
25         }
26 
27     }
28 }

下面是该类的对象定义:

1 <object id="myFilteredIntList" type="GenericsPlay.FilterableList&lt;int>, GenericsPlay">
2   <property name="Name" value="My Integer List"/>
3 </object>

在为泛型类对象指定type属性的时候要注意:第一,左尖括号<要替换成字符串“&lt;”,因为在XML中左尖括号会被认为是小于号。从可读性来讲,我们都知道这并不是理想的方式。第二,type参数值中不能包含程序集的名称,因为程序集名称要求和类型全名用逗号隔开,而在这里逗号已经被用来分隔泛型类的类型参数了。将来可能会用其它字符代替这两个符号,但目前还没找到更具可读性的方案。若要提高可读性,建议使用类型别名,如下所示:

1 <typeAliases>
2  <alias name="GenericDictionary" type=" System.Collections.Generic.Dictionary&lt;,>" />
3  <alias name="myDictionary" type="System.Collections.Generic.Dictionary&lt;int,string>" />
4 </typeAliases>

然后,下面的对象定义:

1 <object id="myGenericObject" 
2         type="GenericsPlay.ExampleGenericObject&lt;System.Collections.Generic.Dictionary&lt;int , string>>, GenericsPlay" />

就可以缩短为:

1 <object id="myOtherGenericObject" 
2         type="GenericsPlay.ExampleGenericObject&lt;GenericDictionary&lt;int , string>>, GenericsPlay" />

或者更短:

1 <object id="myOtherOtherGenericObject" 
2         type="GenericsPlay.ExampleGenericObject&lt;MyIntStringDictionary>, GenericsPlay" />

 

 

posted @ 2017-05-19 11:48  JiYF  阅读(769)  评论(0编辑  收藏  举报