157 recommendations for writing high-quality code to improve C # programs--recommendation 109: Using nested classes with care

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.