如果你想建立一个可以支持数据绑定的自定义集合,那你至少要实现IList接口或IListSource(在Winform环境中。如果在Asp.net的环境中你只需要实现IEnumerable接口就可以了)。
IList接口继承于ICollection接口而ICollection接口又继承于IEnumerable接口。所以当你实现IList接口的时候就同时实现了另外的两个接口。
IEnumerable接口:实现此接口的集合类可以被foreach迭代。
ICollection接口:实现此接口的集合类具有支持集合的基本特性。如:可以查看集合中的元素的总数等。
IList接口:实现此接口的集合类支持数据绑定的最小化实现。也就是说可以被将其数据绑定到UI元素上。(支持最小化的数据绑定功能)
好,大致介绍到这里。还是看代码慢慢讲解吧!
为了完整的说明实现。我们需要建立两个项目其中
1.WindowForm项目:用来测试用。
2.MyCollectionLibary : 类库项目。我在此建立了两个类,一个Person类和People类。
其中 Person 类表示放入到People集合类的集合项目。People类是个集合类,实现了IList接口,用于维持和管理多个Person对象。
这个项目的代码如下:
Person类的实现:
using System;2
using System.Collections.Generic;3
using System.Text;4

5
namespace MyCollectionLibary6
{7
public class Person8
{9
private string _lastname;10

11
public string Lastname12
{13
get { return _lastname; }14
set { _lastname = value; }15
}16
private string firstname;17

18
public string Firstname19
{20
get { return firstname; }21
set { firstname = value; }22
}23
public Person() { }24
public Person(string firstName, string lastName)25
{26
this.Lastname = lastName;27
this.Firstname = firstname;28
}29
}30
}31

1.Person类中只有两个属性(为了保持例子的简单行)。
2.请注意我保留了一个不带任何参数的构造函数,这个构造函数又可能会被数据绑定使用所以请保留下来。(见26行)
People类的实现:
请先using System.Collections命名空间。
public class People : IList ,然后“显示实现接口”(不一定必须要这样做)。
using System;2
using System.Collections;3
using System.Collections.Generic;4
using System.Text;5

6
namespace MyCollectionLibary7
{8
public class People : IList9
{10
ArrayList _list;11
public People()12
{13
_list = new ArrayList();14
}15
IList 成员103

104
ICollection 成员127

128
IEnumerable 成员136
}137
}138

其中需要说明的是:带IList.方法名的方法才是必须要实现的方法。如果你需要是你的类具有自己对应与接口的方法也可以如我在代码中实现的那样来实现。
最后请注意一下IEnumerable.GetEnumerator()方法。我使用的是一种简单的实现方式。如果你需要编写逻辑也可以想如下这样做。
建立一个PeopleEnumerator让它实现IEnumerator接口。
using System;2
using System.Collections.Generic;3
using System.Text;4
using System.Collections;5

6
namespace MyCollectionLibary7
{8
/// <summary>9
/// foreach会使用这个类对People类进行迭代。10
/// </summary>11
public class PeopleEnumerator : IEnumerator12
{13
14
private int _index;15
private IList _list;16
public PeopleEnumerator(IList list)17
{18
_index = -1;19
_list = list;20
}21
IEnumerator 成员44
}45
}46

编写好这个类以后你还需要修改一下People类中的IEnumerable.GetEnumerator()的实现。实现如下:
将原有的代码删除掉,替代为:return new PeopleEnumerator(_list);
就完成了。
接下来你可以下载我完成的Demo看看测试的结果。
代码下载
完成。。。。。。。。。。。。。。。。。。。。。。



浙公网安备 33010602011771号