实现ICollection例子
实现ICollection的范例

自定义
1
using System;
2
using System.Collections;
3
4
namespace 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
using System;2
using System.Collections;3

4
namespace Relaction.Collections5


{6

/**//// <summary>7
/// 8
/// </summary>9
public class MyCollections:ICollection10

{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 IsSynchronized20

{21
get22

{23
return true;24
}25
}26

27
public int Count28

{29
get30

{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 SyncRoot41

{42
get43

{44
return _root;45
}46
}47

48
#endregion49

50

IEnumerable 成员#region IEnumerable 成员51

52
public IEnumerator GetEnumerator()53

{54
return _list.GetEnumerator();55
}56

57
#endregion58
}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
}

浙公网安备 33010602011771号