public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private List<MyClass> iList = new List<MyClass>();
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
MyClass c = new MyClass();
c.IntField = i;
c.StrField = string.Format("string{0}", i);
iList.Add(c);
}
}
private void button2_Click(object sender, EventArgs e)
{
//foreach (MyClass c in iList)
//{
// iList.Remove(c); // 这里会出现问题:集合已修改;可能无法执行枚举操作。
//}
// 用For代替
for (int i = iList.Count - 1; i >= 0; i++)
{
MyClass c = iList[i];
iList.Remove(c);
}
}
class MyClass
{
private int _intField;
public int IntField
{
get { return _intField; }
set { _intField = value; }
}
private string _strField;
public string StrField
{
get { return _strField; }
set { _strField = value; }
}
}
}