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


    建议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个建议》陆敏技

  • 相关阅读:
    404、500、502等HTTP状态码介绍
    Linux系统信息查看命令
    SVN clean up 无法继续
    gitlab使用
    Git SSH Key 生成步骤
    gitlab 杂记
    JS函数
    MySQL基础
    WEB测试方法
    操作系统的发展史
  • 原文地址:https://www.cnblogs.com/farmer-y/p/8000318.html
Copyright © 2020-2023  润新知