The Value Type struct traps in foreach, structforeach
Recently, I stepped on a pitfall. To optimize the code, I changed the class to struct. The result showed that the original initialization statement was not run as expected. The pseudocode is as follows:
Public struct A {bool _ isActive; public void Init (bool isActive) {_ isActive = isActive ;}}
Public A [] _ arrayA; // call the following foreach A in _ arrayA) {a. Init ();}
It looks like it can meet expectations, but it is not actually.
In foreach, a temporary variable is usually copied. The difference is that the value type copies a new value type and the new value type changes, it is not the content in the array. However, the referenced content copied from the reference type still references the reference of the same content. Therefore, all the operations performed by using the newly copied reference will be applied to the expected content.
Therefore, you still need to use the for loop to replace foreach.
For (int I = 0; I <_ arrayA. Length; I ++) {_ arrayA [I]. Init ();}
If you want to learn more about this, we recommend the following articles:
Http://stackoverflow.com/questions/5663783/in-net-using-foreach-to-iterate-an-instance-of-ienumerablevaluetype-will-c