When I wrote an article about using GDI + for animation yesterday, I thought about streamlining the code, so I used the point structure of the system to replace a class defined by myself, the result is a problem.
// Before modification, pqueue is an object inherited from the queue <p> class.
// Class P contains only two int attributes X and Y.
Foreach (P in pqueue)
{
P. x = p. x-1; // No error message
}
// After modification, pqueue is an object inherited from the queue <point> class
Foreach (system. Drawing. point P in pqueue)
{
P. x = p. x-1; // the error message is displayed. "P" is a "foreach" Iteration variable and cannot be modified.
}
It's strange. Why is it wrong to change one? Then I searched for foreach on the Internet. I saw that msdn and many posts mentioned two restrictions on the use of the foreach statement: the enumeration members cannot be modified, and the set should not be deleted.
It turned out to be the limitations of foreach itself, but if I thought it was wrong, it was all enumeration members. What kind of class can I write like this? What kind of structure is wrong? It seems that something is different. Search for "C # class structure difference" and find out the cause. The class is of the reference type, while the structure is of the value type. That is to say, when a class variable is used as an iteration variable, foreach only obtains its reference, that is, the reference is the address, not itself, you can modify the members of a struct variable as long as the address remains unchanged. When a struct variable is used as an iteration variable, foreach obtains the variable itself, and the member that modifies the variable is to modify it, it's changed, and foreach won't be able to recognize it. How can the iterator movenext be?
For foreach restrictions, the Internet seems to use an int array as an example, because Int Is of the value type just like struct, and neither of them nor their members can be modified, however, this is only one type and cannot represent all types, because there are also reference types, which are easy to misunderstand. Therefore, the use restrictions of the foreach statement should be written as follows:
1. You cannot modify the enumerated member. However, if the enumerated member belongs to the reference type, you can modify its own member;
2. Do not delete a set.