体验C#范型,创建指定元素类型的ArrayList

体验C#范型,创建指定元素类型的ArrayList
范型是一种重要的面向对象机制,了解C++的应该对他十分熟悉。简单的说来,范型机制就是一种将类型延后到运行是确定的机制。比如你在定义一个类是,可以不指定某个字段或属性的类型,而此类型将在类的实例声明时被确定。在.net2005中,加入了对c#和vb.net的范型支持,为开发带来了很大的便利。
举个例子:
1public class Info
2 {
3 private T info;
4 public Info(T ainfo)
5 {
6 this.info = ainfo;
7 }
8
9 public void ShowInfo()
10 {
11 Console.WriteLine(
12 this.info.ToString());
13 }
14 }class Program
{
static void Main(string[] args)
{
Info a = new Info (10);
Info day = new Info (DateTime.Now);
a.ShowInfo();
day.ShowInfo();
}
}
可以看见,类在定义时,成员info的类型用“T”代替,在对象声明时,"T"的真正所指才被给出。

在..Net2005中,.类库中加入了许多对范型的支持,在 System.Collections.Generic中,其中包括基于范型的SortedList,Queue,Stach等等,但是却没有我们平常使用最多的ArrayList,如果有这样的东西,我们就能在建立ArrayList时指定元素的类型,而每次提取时就不用进行强制类型转换了。有了这样的想法,我们可以自己动手作一个。

首先现明确目标的功能:实现ArrayList中的插入、删除,最重要的是:指定类型的元素的插入,和基于下标的元素的获得。实现起来很简单,只要使用一个对象适配器的模式。


1 public class ZLink :IEnumerable
2 {
3 private ArrayList list;
4 public int Count
5 {
6 get
7 {
8 return this.list.Count;
9 }
10 }
11 public ZLink()
12 {
13 this.list = new ArrayList();
14 }
15
16 public void Add(T item)
17 {
18 this.list.Add(item);
19 }
20
21 public T this[int i]
22 {
23 get
24 {
25 try
26 {
27 return (T)this.list[i];
28 }
29
30 catch (Exception ex)
31 {
32 throw ex;
33 }
34 }
35 }
36
37 public void Remove(T item)
38 {
39 this.list.Remove(item);
40 }
41
42 public void RemoveAt(int i)
43 {
44 try
45 {
46 this.list.RemoveAt(i);
47 }
48
49 catch (Exception ex)
50 {
51 throw ex;
52 }
53 }
54
55 public void Sort(IComparer ic)
56 {
57 this.list.Sort(ic);
58 }
59
60 public bool Contains(T item)
61 {
62 return this.list.Contains(item);
63 }
64
65 public void Clear()
66 {
67 this.list.Clear();
68 }
69
70
71 #region IEnumerable Members
72
73 public IEnumerator GetEnumerator()
74 {
75 foreach (object o in this.list)
76 {
77 yield return (T)o;
78 }
79 }
80
81 #endregion
82
83 #region IEnumerable Members
84
85 IEnumerator IEnumerable.GetEnumerator()
86 {
87 return this.GetEnumerator();
88 }
89
90 #endregion
91 }
其中的Add函数只能加入T类型的对象,而通过下标取得的元素也是T类型,另外还实现了在ArrayList中常用的Remove、Contains、Sort等方法。
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 ZLink patlabor = new ZLink ();
6 patlabor.Add(new Man(21));
7 patlabor.Add(new Man(33));
8 patlabor.Add(new Man(28));
9
10 foreach (Man man in patlabor)
11 {
12 Console.WriteLine(man.ToString());
13 }
14 }
15 }
其中的"Man"可以是任何类型。代码中与IEnumerat有关的东西,是为了实现ZLink的foreach功能,这个以后再详细说。


 


.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值