码迷,mamicode.com
首页 > Windows程序 > 详细

【转】编写高质量代码改善C#程序的157个建议——建议109:谨慎使用嵌套类

时间:2017-12-07 21:18:02      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:type   私有   serial   一个   它的   col   isarray   this   obj   

 

建议109:谨慎使用嵌套类

使用嵌套类的原则是:当某类型需要访问另一个类型的私有成员时,才将它实现为嵌套类。一个典型的例子是在实现集合时,要为集合实现迭代器,这时用到了嵌套类。代码如下所示:

public class ArrayList : IList, ICollection, IEnumerable, ICloneable
{
    //省略
    public virtual IEnumerator GetEnumerator()
    {
        return new ArrayListEnumeratorSimple(this);
    }

    [Serializable]
    private sealed class ArrayListEnumeratorSimple : IEnumerator, ICloneable
    {
        //省略
        internal ArrayListEnumeratorSimple(ArrayList list)
        {
            this.list = list;
            this.index = -1;
            this.version = list._version;
            this.isArrayList = list.GetType() == typeof(ArrayList);
            this.currentElement = dummyObject;
        }
    }
}

我们可以注意到,嵌套类ArrayListEnumeratorSimple访问了若干外部类ArrayList的私有成员。

另外需要强调的是,如果必须出现一个嵌套类,应该将其实现为private。也就是说,除了包含它的外部类外,不应该让任何其他类型可以访问到它。嵌套类的服务对象应该属于当前类。

 

 

转自:《编写高质量代码改善C#程序的157个建议》陆敏技

【转】编写高质量代码改善C#程序的157个建议——建议109:谨慎使用嵌套类

标签:type   私有   serial   一个   它的   col   isarray   this   obj   

原文地址:http://www.cnblogs.com/farmer-y/p/8000318.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!