日期:2013-04-12  浏览次数:20391 次

//本文参阅 CSDN ccat 的 MarchLibrary 修改
// C# 1.x 实现 "强类型元素唯一的 ArrayList"
using System;
using System.Collections;

/// 任何元素的 Type 都应当等于指定的类型或为指定类型的子类。
/// 对于值类型,最好先行装箱再使用。
/// 作为 C# 1.x 语言实现泛型功能之前的代用品(运行时错误)。

public class StrongTypeUniqueArrayList : ArrayList
{
private Type _type;
/// <summary>
/// 禁止默认构造。
/// </summary>
private StrongTypeUniqueArrayList()
{
}
/// <summary>
/// 在容器初始化时指定其元素类型
/// </summary>
/// <param name="ElementType">ArrayList (元素)类型</param>
public StrongTypeUniqueArrayList(System.Type ElementType)
{
_type = ElementType;
}
/// <summary>
/// 不能再更改其内部元素类型。
/// </summary>
public Type Type
{
get
{
return _type;
}
}
private bool IsMatchType(Type eType)
{
return (eType == _type)|(eType.IsSubclassOf(_type));
}


public override object this[int index]
{
set
{
if (IsMatchType(value.GetType()))
{
if (base.Contains(value))
{
if (base.IndexOf(value) == index)
{
base[index] = value;
}
else
{
throw new ArgumentException(value.ToString() + " 元素重复","value");
}
}
else
{
base[index] = value;
}
}
else
{
throw new ArgumentException(value.GetType().FullName + " 类型错误", "value");
}
}
}

public override int Add(object value)
{
if (!base.Contains(value) && IsMatchType(value.GetType()))
{
base.Add(value);
return 1;
}
else
{
throw new ArgumentException(value.GetType().FullName + " 类型错误 或 " + value.ToString() + " 元素重复", "value");
//return -1;
}
}
public override void Insert(int index, object value)
{
if (!base.Contains(value) && IsMatchType(value.GetType()))
{
base.Insert(index,value);
}
else
{
throw new ArgumentException(value.GetType().FullName + " 类型错误 或 " + value.ToString() + " 元素重复", "value");
}
}

public override void InsertRange(int index, ICollection c)
{
System.Collections.IEnumerator ie = c.GetEnumerator();
while (ie.MoveNext())
{
if (base.Contains(ie.Current) || !IsMatchType(ie.Current.GetType()))
{
throw new ArgumentException(ie.Current.GetType().FullName + " 类型错误 或 " + ie.Current.ToString() + " 元素重复", "c");
}
}
base.InsertRange(index,c);
}
public override void SetRange(int index, ICollection c)
{
System.Collections.IEnumerator ie = c.GetEnumerator();
int i = 0;
while (ie.MoveNext())
{
if (IsMatchType(ie.Current.GetType()))
{
if (base.Contains(ie.Current) && base.IndexOf(ie.Current) != i)
{
throw new ArgumentException(ie.Current.ToString() + " 元素重复","c");
}
}
else
{
throw new ArgumentException(ie.Current.GetType().FullName + " 类型错误", "c");
}
i++;
}
base.SetRange(index,c);
}
public override void AddRange(ICollection c)
{
System.Collections.IEnumerator ie = c.GetEnumerator();
while (ie.MoveNext())
{
if (base.Contains(ie.Current) || !IsMatchType(ie.Current.GetType()))
{
throw new ArgumentException(ie.Current.GetType().FullName + " 类型错误 或 " + ie.Current.ToString() + " 元素重复", "c");
}
}
base.AddRange(c);
}
}
//Test:
public class Class1
{
private static int i = 0;
public string xxx = "