同时具备IList和IDictionary的特点的集合

     [Serializable]
public class MyCollection:IList
{
private readonly Dictionary<string, MyItem> _dicMyItems;
private readonly List<MyItem> _myList;
//private readonly MyUIList _parent; public MyCollection() : this(null)
{ } public MyCollection(MyUIList parent)
{
//_parent = parent;
_myList = new List<MyItem>();
_dicMyItems = new Dictionary<string, MyItem>(StringComparer.InvariantCultureIgnoreCase);
} public MyItem this[string key]
{
get
{
MyItem item;
_dicMyItems.TryGetValue(key, out item);
if (item != null && item.Name == null)
{
return null;
}
return item;
}
} public IEnumerator GetEnumerator()
{
return _myList.GetEnumerator();
} public void CopyTo(Array array, int index)
{
_myList.CopyTo((MyItem [])array, index);
} public int Count
{
get { return _myList.Count; }
private set {}
} public object SyncRoot { get; private set; }
public bool IsSynchronized { get; private set; }
public int Add(object value)
{
return AddHelper((MyItem)value);
} public bool Contains(object value)
{
return _myList.Contains(Cast(value));
} public void Clear()
{
_myList.Clear();
_dicMyItems.Clear();
} public int IndexOf(object value)
{
return _myList.IndexOf((MyItem)value);
} public void Insert(int index, object value)
{
if (value == null)
{
return;
} MyItem item = Cast(value);
Insert(index, item);
} public void Remove(object value)
{
Remove(Cast(value));
} public void RemoveAt(int index)
{
if (index >= _myList.Count)
return;
Remove(_myList[index]);
} public object this[int index]
{
get { return _myList[index]; }
set { _myList[index] = Cast(value); }
} public bool IsReadOnly { get; private set; }
public bool IsFixedSize { get; private set; } private int AddHelper(MyItem item)
{
if (item == null)
throw new ArgumentNullException("item");
if (string.IsNullOrEmpty(item.Name) || _dicMyItems.ContainsKey(item.Name))
{
throw new Exception("name is null or name already exists");
}
//item.Parent = _parent;
int retVal = _myList.Count;
_myList.Add(item);
AddItemToDictionary(item);
return retVal;
} private void AddItemToDictionary(MyItem item)
{
_dicMyItems.Add(item.Name, item);
} private MyItem Cast(object value)
{
if (value == null)
{
throw new ArgumentNullException("value");
} var item = value as MyItem; if (item == null)
throw new ArgumentException("DriverItem"); return item;
} public void Insert(int index, MyItem item)
{
if (item == null)
throw new ArgumentNullException("item");
if (string.IsNullOrEmpty(item.Name) || _dicMyItems.ContainsKey(item.Name))
{
throw new Exception("name is null or name already exists");
}
//item.Parent = _parent;
_myList.Insert(index, item);
AddItemToDictionary(item);
} public void Remove(MyItem item)
{
_myList.Remove(item);
_dicMyItems.Remove(item.Name);
}
}

MyCollection

其中 MyItem为自己定义的数据结构,可以换成自己的,或者改为通用型的T泛型

如果对你有帮助,请顶一下

作者:紫之荆

出处:http://www.cnblogs.com/zizhijing/

欢迎转载

05-11 13:42