Recommendation 24: Iterators should be read-only
If observed, the iterator in the FCL has only the GetEnumerator method, there is no Setenumerator method, and all the collection classes do not have an iterator property that can be written. There are two reasons:
A: This violates the design mode of the opening and closing principle. Iterators that are set to the collection may directly cause the behavior of the collection to be abnormal or changed. Once a new iteration requirement is really needed, it is entirely possible to create a new iterator that satisfies the requirements, rather than setting the iterator for the collection, because doing so directly results in an unknowable behavior for other iterative scenarios that use the collection object.
Two: Now, we have LINQ. With LINQ, you can meet any iteration needs without creating any new types.
If the iterator is writable, the hazard example is as follows:
Assuming there is a common collection object, there are two business classes that need to operate on that collection.
Business Class A is only responsible for displaying element iterations to the UI:
Private New MyList (); Private Imyenumerator enumerator = list. GetEnumerator (); while (Enumerator. MoveNext ()) { int current = Enumerator. Current; Console.WriteLine (current. ToString ()); }
Business Class B to implement a new iterator for the collection object, for one of its own needs:
Private New as MyList); as MyList). Setenumerator (Enumerator2); while (Enumerator2. MoveNext ()) { int current = Enumerator2. Current; Console.WriteLine (current. ToString ()); }
Now go back to business Class A to perform an iteration, and the result will be the iterator output set by B. This is equivalent to B interference in the absence of notification A, which should be avoided.
In fact, the above code will work fine even without the following line of code:
as MyList). Setenumerator (ENUMERATOR2);
Therefore, do not set writable properties for iterators.
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--recommendation 24: iterators should be read-only