//最近忙着搬家,不好意思.献丑了:)
//本示例主要是增加了其对"要求唯一性","限定类型","合集","并集","交集"支持.
//你可以看看相关的MSDN.
using System;
using System.Collections;
namespace Com.LinFeng.Common
{
public class ExtendedCollection :CollectionBase,IExtendedCollection
{
protected Type _type;
protected bool _unique;
public ExtendedCollection(Type type,bool unique)
{
this._type=type;
this._unique=unique;
}
public ExtendedCollection(Type type):this(type,false){}
public ExtendedCollection(bool unique):this(null,unique){}
public ExtendedCollection():this(null,false){}
public virtual int Add(object value)
{
if(this._type!=null && (!this._type.IsInstanceOfType(value)))
{
throw new ArgumentException("类型不正确.","value");
}
if(this._unique ==true && this.Contains(value))
{
throw new ArgumentException("禁止插入重复元素.","value");
}
else
{
return List.Add(value);
}
}
public virtual bool Insert(int index,object value)
{
if(!(this._type==null || this._type.IsInstanceOfType(value)))
{
throw new ArgumentException("类型不正确.","value");
}
if(this._unique ==true && this.Contains(value))
{
throw new ArgumentException("禁止插入重复元素.","value");
}
else
{
List.Insert(index,value);
return true;
}
}
public virtual void Remove(object value)
{
List.Remove(value);
}
public virtual bool Contains(object value)
{
return List.Contains(value);
}
public virtual int IndexOf(object value)
{
return List.IndexOf(value);
}
public virtual object this[int index]
{
get
{
return (object)List[index];
}
set
{
if(!(this._type==null || this._type.IsInstanceOfType(value)))
{
throw new ArgumentException("类型不正确.","this["+index+"]");
}
if(this._unique ==true && this.Contains(value))
{
throw new ArgumentException("禁止插入重复元素.","this["+index+"]");
}
else
{
List[index]=value;
}
}
}
#region IExtendedCollection 成员
public void Merge(ICollection collection)
{
foreach(object item in collection)
{
if(!this.Contains(item))
{
this.Add(item);
}
}
}
public void Subtract(ICollection collection)
{
foreach(object item in collection)
{
if(this.Contains(item))
{
this.Remove(item);
}
}
}
public void Intersect(ICollection collection)
{
foreach(object item in this)
{
if(!this.Contains(item))
{
this.Remove(item);
}
}
}
public class YourObject
{
public string Prop1 {...}
public string Prop2 {...}
}
ArrayList al = new ArrayList();
YourObject yo = new YourObject();
yo.Prop1 = "...";
yo.Prop2 = "...";
al.Add(yo);
Session["Data"] = al;
或在Data Access层
ArrayList al = new ArrayList();
SqlDataReader dr = ...;
while (dr.Read())
{
YourObject yo = new YourObject();
yo.Prop1 = dr["ColumnName"].ToString();
...
al.Add(yo);
}
dr.Close();
return al;