引用型变量和值类型变量在foreach中的区别
对于值类型变量,迭代变量不可更改。
对于引用型变量,迭代变量可以更改,但是不可以删除。
public partial class MainForm :
{
List<int> iNum = new List<int>();
List<Object> oPerson = new List<object>();
//foreach--- Reference Type 和 Value Type
private void simpleButton2_Click(object sender, EventArgs e)
{
iNum.Add(1);
iNum.Add(2);
Person person1 = new Person();
person1.Age = 25;
Person person2 = new Person();
person2.Age = 26;
oPerson.Add(person1);
oPerson.Add(person2);
//编译时无法通过----错误代码
foreach (int i in iNum){
i = 10;
}
// 成功修改
foreach (Person o in oPerson){
o.Age = 50;
}
}
}
public class Person
{
private int iAge;
public int Age
{
get{return iAge;}
set{iAge =value;}
}
{
List<int> iNum = new List<int>();
List<Object> oPerson = new List<object>();
//foreach--- Reference Type 和 Value Type
private void simpleButton2_Click(object sender, EventArgs e)
{
iNum.Add(1);
iNum.Add(2);
Person person1 = new Person();
person1.Age = 25;
Person person2 = new Person();
person2.Age = 26;
oPerson.Add(person1);
oPerson.Add(person2);
//编译时无法通过----错误代码
foreach (int i in iNum){
i = 10;
}
// 成功修改
foreach (Person o in oPerson){
o.Age = 50;
}
}
}
public class Person
{
private int iAge;
public int Age
{
get{return iAge;}
set{iAge =value;}
}
}
posted on 2011-06-22 16:22 WildFlower 阅读(488) 评论(0) 编辑 收藏 举报