static void Main(string[] args)
{
Person[] stu = new Person[3];
for (int i = 0; i < 3; i++)
{
stu[i] = new Person();
}
//foreach (Person i in stu)
//{
// i = new Person();
//} stu[0].name = "苍井空";
stu[1].name = "金贞娥";
stu[2].name = "汤姆";
stu[0].work();
stu[1].work();
stu[2].work();
Console.ReadKey();
}
}
class Person
{
public string name;
public void work()
{
Console.WriteLine(name);
}
}在上面代码中,使用for循环全部new对象,为什么使用注释的foreach循环,就不行呢?for循环里面的i和foreach里面的i都是迭代变量吧,为什么前者行,后者不行.....谢谢!!!
{
Person[] stu = new Person[3];
for (int i = 0; i < 3; i++)
{
stu[i] = new Person();
}
//foreach (Person i in stu)
//{
// i = new Person();
//} stu[0].name = "苍井空";
stu[1].name = "金贞娥";
stu[2].name = "汤姆";
stu[0].work();
stu[1].work();
stu[2].work();
Console.ReadKey();
}
}
class Person
{
public string name;
public void work()
{
Console.WriteLine(name);
}
}在上面代码中,使用for循环全部new对象,为什么使用注释的foreach循环,就不行呢?for循环里面的i和foreach里面的i都是迭代变量吧,为什么前者行,后者不行.....谢谢!!!
foreach用于遍历实现IEnumerable接口的集合的元素
简洁
{
static int leijia()
{
int[] num = new int[5] { 1, 2, 3, 4, 5 };
int sum = 0;
foreach (int i in num)
{
sum += i;
}
return sum;
}
public static void Main()
{
int number = leijia();
Console.WriteLine(number);
Console.ReadKey();
}
}这个foreach内部算不算赋值呢?还是有“=”号
object j = i;
j = 10;这也不会把i变为10啊!
object j = i;
j = 10;