What is the difference between the generic foreach method and the foreach statement?
List <person> lst = new list <person> ();
Lst. foreach (delegate (person P)
{
P = NULL; // No error is reported, but the object value is not changed.
P = new item (); // No error is reported, but the object value is not changed
});
Lst. foreach (P => P = new item (); // No error is reported, but the object value is not changed.
Bytes -------------------------------------------------------------------------------------------------------------
Foreach (person P in lst)
{
P = NULL; // The compilation fails. The iteration variable cannot be assigned a value.
}
Why does the generic foreach method assign values to P directly without an error?
The effect of foreach is equivalent:
-
C # code
-
Action<Person> act = p => p = new item(); foreach (Person p in lst) { act(p); }
The copy passed to the method is a copy of P (for the reference type, it is a copy of its reference address), so the value assigned to it does not affect the original value.
For foreach blocks that cannot assign values to P, refer to the running principle of foreach (ienumerable interface)
Http://www.cnblogs.com/xiaopin/archive/2011/01/08/1930535.html
Http://topic.csdn.net/u/20110702/23/ab1ddfaf-0576-409f-aed5-b24ab10046e6.html