zoukankan      html  css  js  c++  java
  • .NET架构小技巧(2)——访问修饰符正确姿势

      在C#中,访问修饰符是使用频率很高的一组关键字,一共四个单词六个组合:public,internal,protected internal,protected,private protected,private,如果你对这些关键字非常清楚,请跳过,节省时间;如果你在编程中一般都使用public和private,那不防花点时间来明确一下,方便设计功能模块时准备使用。

     

     

      如果简单的分层.net程序集(dll,exe)的话,如上图,修饰符用在自定义类型前和类内部的成员前(方法,属性,字段等),自定义类型只能使用internal和public,类内部成员七种修饰符都可以使用的。

      接下来,唠叨一下七种使用场景:

      public:这个什么场景都可以使用

      internal:只能在当前的应用程序集内使用

      protected:只能在子类中使用父类中的protected成员

      private:只能在当前类中使用private成员

      protected internal:在当前程序集内使用和不在一个程序集内的子类中使用

      private protected:只能在当前程序集内的子类中使用

      准确的使用访问修饰符,可以很好的封装对象的功能,该对外暴露的暴露,该开放的开放,开放的多彻底都可以控制。

      例如:

    public class Program
    {
        static void Main(string[] args)
    {
            var myList = new MyList<int>();
            myList.Add(1);
            myList.Add(2);
            myList.Add(3);
            myList.Add(4);
            myList.Add(5);
            foreach (var o in myList)
            {
                Console.WriteLine(o);
            }
        }
    }
    
    public class MyList<T> : IEnumerable
    {
        protected T[] array;
        public MyList()
    {
            array = new T[4];
        }
        public int Count
        {
            get;
            private set;
        } = 0;
    
        public void Add(T t)
    {
            if (array.Length == Count)
            {
                array = CreateNewArray(array, Count * 2);
            }
            array[Count] = t;
            Count++;
        }
    
        public IEnumerator GetEnumerator()
    {
            for (int i = 0; i < Count; i++)
            {
                yield return array[i];
            }
        }
        private T[] CreateNewArray(T[] oldArray, int length)
        {
            var newArray = new T[length];
            oldArray.CopyTo(newArray, 0);
            return newArray;
        }
    }

      其中,CreateNewArray方法只在内部使用,所以是Private;Add方法是供外部添加元素的,public;Count属性get是对外提供元素的个数,但set是私有的,不能在外部对它赋值;字段array按理该是private,这里我想让子类能访问到,以便提供更大的访问权限,官方的List<T>是private的,子类中是看不见这个数据的。这个例子就能很好的说明:准确的使用访问修饰符,可以很好的封装对象的功能,该对外暴露的暴露,该开放的开放。

      另一方面,规(节)范(操)也很重要!

      想要更快更方便的了解相关知识,可以关注微信公众号 
     

     

     

  • 相关阅读:
    VS2010 error LNK2019: 无法解析的外部符号
    strspn()函数的使用方法
    直接插入排序
    opecv 常用的函数
    matlab中 fprintf 和disp的用法
    面试经历
    挚爱 泰戈尔
    见与不见
    无题
    Cannot create PoolableConnectionFactory (Could not create connection to database server.
  • 原文地址:https://www.cnblogs.com/ljknlb/p/15854613.html
Copyright © 2011-2022 走看看