比如这样: public partial class Form1 : Form { private ArrayList list; public Form1() { InitializeComponent(); } public void Add(string text) { this.list.Add(text); } }
自定义一个item类. 里面含size,value,一个object数组.定义一个更长的数组 new object[size+1] 然后把原来的clone进去.再把最后一个值加入.这样就实现了add操作.
for example: class MyList { //保存列表元素 private object[] elements; //列表长度 private int count; public int Count { get { return this.count; } } public MyList() { elements = new object[0]; count = 0; } public object this[int index] { get { if (index < 0 || index >= count) { throw new IndexOutOfRangeException(); } return elements[index]; } set { if (index < 0 || index >= count) { throw new IndexOutOfRangeException(); } this.elements[index] = value; } } //实现Add方法 public int Add(object obj) { count ++; object[] objs = new object[count]; for (int i = 0; i < elements.Length; i++) { objs[i] = elements[i]; } objs[count - 1] = obj; elements = objs; return count; } }测试: MyList list = new MyList(); list.Add("aaa"); list.Add("bbb"); list.Add("ccc"); for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i].ToString()); } //没试更改 list[1] = "ddd"; for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i].ToString()); }输出: aaa bbb ccc aaa ddd ccc
class myList : System.Collections.ArrayList
{
public void Add(int value, string text)
{
}
}
public partial class Form1 : Form
{
private ArrayList list;
public Form1()
{
InitializeComponent();
}
public void Add(string text)
{
this.list.Add(text);
}
}
{
if (this._size == this._items.Length)
{
this.EnsureCapacity(this._size + 1);
}
this._items[this._size] = value;
this._version++;
return this._size++;
}另外说明一下ArrayList内部用object数组来存储
如果用来存储值类型,需要多次装箱、拆箱,性能会非常低
里面含size,value,一个object数组.定义一个更长的数组
new object[size+1]
然后把原来的clone进去.再把最后一个值加入.这样就实现了add操作.
{
//保存列表元素
private object[] elements;
//列表长度
private int count; public int Count
{
get
{
return this.count;
}
}
public MyList()
{
elements = new object[0];
count = 0;
} public object this[int index]
{
get
{
if (index < 0 || index >= count)
{
throw new IndexOutOfRangeException();
}
return elements[index];
}
set
{
if (index < 0 || index >= count)
{
throw new IndexOutOfRangeException();
}
this.elements[index] = value;
}
} //实现Add方法
public int Add(object obj)
{
count ++;
object[] objs = new object[count];
for (int i = 0; i < elements.Length; i++)
{
objs[i] = elements[i];
}
objs[count - 1] = obj;
elements = objs;
return count;
}
}测试:
MyList list = new MyList();
list.Add("aaa");
list.Add("bbb");
list.Add("ccc");
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i].ToString());
}
//没试更改
list[1] = "ddd";
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i].ToString());
}输出:
aaa
bbb
ccc
aaa
ddd
ccc