实现ICollection例子
实现ICollection的范例
自定义
1using System;
2using System.Collections;
3
4namespace Relaction.Collections
5{
6 /**//// <summary>
7 ///
8 /// </summary>
9 public class MyCollections:ICollection
10 {
11 private string[] _list;
12 private object _root = new object();
13 public MyCollections()
14 {
15 _list = new string[3]{"1","2","3"};
16 }
17 ICollection 成员#region ICollection 成员
18
19 public bool IsSynchronized
20 {
21 get
22 {
23 return true;
24 }
25 }
26
27 public int Count
28 {
29 get
30 {
31 return _list.Length;
32 }
33 }
34
35 public void CopyTo(Array array, int index)
36 {
37 _list.CopyTo(array,index);
38 }
39
40 public object SyncRoot
41 {
42 get
43 {
44 return _root;
45 }
46 }
47
48 #endregion
49
50 IEnumerable 成员#region IEnumerable 成员
51
52 public IEnumerator GetEnumerator()
53 {
54 return _list.GetEnumerator();
55 }
56
57 #endregion
58 }
59}
60
客户代码:1using System;
2using System.Collections;
3
4namespace Relaction.Collections
5{
6 /**//// <summary>
7 ///
8 /// </summary>
9 public class MyCollections:ICollection
10 {
11 private string[] _list;
12 private object _root = new object();
13 public MyCollections()
14 {
15 _list = new string[3]{"1","2","3"};
16 }
17 ICollection 成员#region ICollection 成员
18
19 public bool IsSynchronized
20 {
21 get
22 {
23 return true;
24 }
25 }
26
27 public int Count
28 {
29 get
30 {
31 return _list.Length;
32 }
33 }
34
35 public void CopyTo(Array array, int index)
36 {
37 _list.CopyTo(array,index);
38 }
39
40 public object SyncRoot
41 {
42 get
43 {
44 return _root;
45 }
46 }
47
48 #endregion
49
50 IEnumerable 成员#region IEnumerable 成员
51
52 public IEnumerator GetEnumerator()
53 {
54 return _list.GetEnumerator();
55 }
56
57 #endregion
58 }
59}
60
客户代码
1 private void button7_Click(object sender, System.EventArgs e)
2 {
3 Relaction.Collections.MyCollections c = new Relaction.Collections.MyCollections();
4 foreach(string s in c)
5 {
6 label1.Text += s.ToString();
7 }
8 }
1 private void button7_Click(object sender, System.EventArgs e)
2 {
3 Relaction.Collections.MyCollections c = new Relaction.Collections.MyCollections();
4 foreach(string s in c)
5 {
6 label1.Text += s.ToString();
7 }
8 }