Web-based data, said that foreach can not change the iteration variables, only access to iterate variables. Self-understanding is not very deep, through a few code validation, found that the use of foreach is also a bit special
Verification Method:
1. The iteration variable is int
Int[] Argint = {12,12,12,12,12};
foreach (int item in Argint)
{
item = 100;
}
Result: Compile does not pass, hint item is iteration variable, cannot assign value to it;
2. The iteration variable is a struct
public struct MYSTRUCT
{
public string Name {get; set;}
}
mystruct[] array = new mystruct[] {new MyStruct {name = "1"}, new MyStruct {name = "2"}};
foreach (MyStruct item in array)
{
Item. Name= "Test";
}
Result: Compile does not pass, hint item is iteration variable, cannot change its member;
3. Iterate over variables as classes
ilist<student> list = db. Students.tolist ();
foreach (Student item in list)
{
item.address = "xxxxxx";
Item.age = 100;
item.id = 1000;
Item.name = "xxxxx";
Item.sex = 1;
}
Result: The compilation passed, and after execution, the properties of item were changed.
Summary: For cases where the iteration variable is a class, foreach can change the properties of the iteration variable during the iteration.
C # foreach Useful method specifically explains