// No.1
ArrayList list = new ArrayList();
Data d = new Data();
for (int index = 0 ; index < 10 ; index++)
{
d.DataValue = index;
list.Add(d);
}
foreach (Data dumpData in list)
{
System.Diagnostics.Debug.WriteLine(string.Format("list.Add Data={0}", dumpData.DataValue));
}
// No.2
list.Clear();
for (int index = 0; index < 10; index++)
{
Data d2 = new Data();
d2.DataValue = index;
list.Add(d2);
}
foreach (Data dumpData in list)
{
System.Diagnostics.Debug.WriteLine(string.Format("list.Add new Data={0}", dumpData.DataValue));
}
// No.3
list.Clear();
for (int index = 0; index < 10; index++)
{
list.Add(new Data(index));
}
foreach (Data dumpData in list)
{
System.Diagnostics.Debug.WriteLine(string.Format("list.Add new2 Data={0}", dumpData.DataValue));
}
// No.4
list.Clear();
d = new Data();
for (int index = 0; index < 10; index++)
{
d.DataValue = index;
list.Add(d.Clone());
}
foreach (Data dumpData in list)
{
System.Diagnostics.Debug.WriteLine(string.Format("list.Add AddClone={0}", dumpData.DataValue));
}
// No.5
MyArrayList mylist = new MyArrayList();
d = new Data();
for (int index = 0; index < 10; index++)
{
d.DataValue = index;
mylist.MyAdd(d);
}
foreach (Data dumpData in list)
{
System.Diagnostics.Debug.WriteLine(string.Format("mylist.Add MyAdd={0}", dumpData.DataValue));
}
実行結果。
list.Add Data=9
list.Add Data=9
list.Add Data=9
list.Add Data=9
list.Add Data=9
list.Add Data=9
list.Add Data=9
list.Add Data=9
list.Add Data=9
list.Add Data=9
list.Add new Data=0
list.Add new Data=1
list.Add new Data=2
list.Add new Data=3
list.Add new Data=4
list.Add new Data=5
list.Add new Data=6
list.Add new Data=7
list.Add new Data=8
list.Add new Data=9
list.Add new2 Data=0
list.Add new2 Data=1
list.Add new2 Data=2
list.Add new2 Data=3
list.Add new2 Data=4
list.Add new2 Data=5
list.Add new2 Data=6
list.Add new2 Data=7
list.Add new2 Data=8
list.Add new2 Data=9
list.Add AddClone=0
list.Add AddClone=1
list.Add AddClone=2
list.Add AddClone=3
list.Add AddClone=4
list.Add AddClone=5
list.Add AddClone=6
list.Add AddClone=7
list.Add AddClone=8
list.Add AddClone=9
mylist.Add MyAdd=0
mylist.Add MyAdd=1
mylist.Add MyAdd=2
mylist.Add MyAdd=3
mylist.Add MyAdd=4
mylist.Add MyAdd=5
mylist.Add MyAdd=6
mylist.Add MyAdd=7
mylist.Add MyAdd=8
mylist.Add MyAdd=9
使ったクラスはこちらです。
public class Data : ICloneable
{
private int _dataValue;
public int DataValue
{
get { return _dataValue; }
set { _dataValue = value; }
}
public Data()
{
}
public Data(int value)
{
_dataValue = value;
}
#region ICloneable メンバ
public object Clone()
{
Data cloneData = new Data(this.DataValue);
return cloneData;
}
#endregion
}
public class MyArrayList : ArrayList
{
public void MyAdd(ICloneable addValue)
{
Add(addValue.Clone());
}
}