【C#】ArrayList使用汇总
一、ArrayList转换为数组
(1)方法1
ArrayList List = new ArrayList();
Int32[] values = (Int32[])List.ToArray(typeof(Int32));
(2)方法2
ArrayList List = new ArrayList();
Int32[] values = new Int32[List.Count];
List.CopyTo(values);
二、初始化List<ArrayList>
正确写法:
for (int i = 0; i < 32; i++) { ArrayList tmpWaveDataSource = new ArrayList(); List1.Add(tmpWaveDataSource); ArrayList tmpDataSource = new ArrayList(); List2.Add(tmpDataSource); }
错误写法:
for (int i = 0; i < 32; i++) { ArrayList tmpDataSource = new ArrayList(); List1.Add(tmpDataSource); List2.Add(tmpDataSource); }
三、List<ArrayList>元素赋值
List<ArrayList> List1 = new List<ArrayList>();
List<ArrayList> List2 = new List<ArrayList>();
若ArrayList的元素是自定义类(引用对象),把List2的元素添加到List1时,不能直接添加,否则两个List的值会同时改变.如:
int index = 0;
for (int j = 0; j < 6; j++) { List1[index].Add(new Record(0, (List1[index].Count + 1).ToString(), tmpvalue1)); List2[index].Add(new Record(0, (List2[index].Count + 1).ToString(), tmpvalue2)); } public class Record { int id; string xData; double yData; public Record(int id, string xData, double yData) { this.id = id; this.xData = xData; this.yData = yData; } public int ID { get { return id; } set { id = value; } } public string XData { get { return xData; } set { xData = value; } } public double YData { get { return yData; } set { yData = value; } } }
添加元素:
//错误写法: List1[0].Add(List2[0][0]); //正确写法: string dataX = ((Record)List2[0][0]).XData; double dataY = ((Record)List2[0][0]).YData; List1[0].Add(new Record(0, dataX, dataY));
/*******相与枕藉乎舟中,不知东方之既白*******/