自定义集合类
在我们编程的时候经常会用到自定义的class,有的时候需要用到这个class的集合,在实际操作中,仅仅使用数组或List<>不能全面的实现我们所需要的功能,下面介绍一种比较简单好用的写法
程序代码: //在这里继承的IComparable是为了实现集合的Sort()功能
class UserDate : IComparable
{
public UserDate(string key, string value)
{
this.Key = key;
this.Value = value;
}
string _key = string.Empty, _value = string.Empty;
public string Key
{
get { return _key; }
set { _key = value; }
}
public string Value
{
get { return _value; }
set { _value = value; }
}
#region IComparable 成员
public int CompareTo(object obj)
{
UserDate compDate = obj as UserDate;
return this.(compDate.Key);
}
#endregion
}
//关键是要继承CollectionBase,大家可以去看一下继承了CollectionBase类之后,这个集合有了很多的方法
class UserDateCollection : CollectionBase
{
public UserDate this[int index] { get { return (UserDate)List[index]; } set { List[index] = value; } }
//在这里可以做很多事件,比如像Hashtable一样,同样的key只能出现一次
//int index = this.IndexOf(value.Key); if (index != -1) { throw new Exception("...");}
//简单解释一下吧,先检查这个集合是不是有同样的key出现,如果有,则返回一个错误,实际使用时请配合try{}
public void Add(UserDate value)
{
List.Add(value);
}
//这里写法比较灵活,按照自己的思路实现在集合中快速的查找想应的数据
public int Index(string key)
{
for (int i = 0; i < this.Count; i++)
{
if (this[i].Key == key)
return i;
}
return -1;
}
}







