Recommendation 109: Use nested classes with caution
The principle of using nested classes is that when a type needs to access a private member of another type, it is implemented as a nested class. A typical example is when implementing a collection to implement Iterators for a collection, when nested classes are used. The code looks like this:
Public classarraylist:ilist, ICollection, IEnumerable, icloneable{//omitted Public VirtualIEnumerator GetEnumerator () {return NewArraylistenumeratorsimple ( This); } [Serializable]Private Sealed classArraylistenumeratorsimple:ienumerator, ICloneable {//omitted Internalarraylistenumeratorsimple (ArrayList list) { This. List =list; This. Index =-1; This. Version =list._version; This. isarraylist = list. GetType () = =typeof(ArrayList); This. currentelement =Dummyobject; } }}
We can note that the nested class Arraylistenumeratorsimple accesses the private members of several external class ArrayList.
It is also important to emphasize that if a nested class must appear, it should be implemented as private. That is, in addition to the outer class that contains it, you should not let any other type have access to it. The service object for the nested class should belong to the current class.
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 109: Using nested classes with care