欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浅谈C#基础之类的访问修饰符

程序员文章站 2023-12-09 18:16:39
1.类中成员的访问修饰符 方位修饰符就是确定该成员能够访问(使用)的区域。c#中常用的有如下修饰符:pubic(公有)、private(私有)、internal(内联)、...

1.类中成员的访问修饰符

方位修饰符就是确定该成员能够访问(使用)的区域。c#中常用的有如下修饰符:pubic(公有)、private(私有)、internal(内联)、protected(受保护)。举例说明各个修饰符的限制区域。   

复制代码 代码如下:

class testclass
    {
        public int a = 0;
        private int b = 0;
        protected int c = 0;

pulic  static  int d=0;
    }    


testclass类中变量a是公有类型,可以在类外方位,即类实例化后可以使用a;变量b只能在类内访问,即类内部的函数可以使用b;变量c则是testclass继承类可以使用。
复制代码 代码如下:

    class b
    {
        private void st()
        {
           testclass tec = new testclass();
            int aa = tec.a;   //right
            int bb = tec.b;  //wrong
            int cc = tec.c    //wrong
        }

   testclass 实例化对象tec,tec可以访问a但不能访问b、c。那么什么情况下可以访问b、c呢?
复制代码 代码如下:

    class c:testclass
    {
        private void st()
        {
           testclass tec = new testclass();
            c bo = new c();
            int aa = tec.a;
            int bb = tec.b;//wrong
            int cc = tec.c;//wrong
            int tt = bo.c;
        }
    }

先说c。c是受保护类型,其继承类c可以访问。是类b实例化对象仍然不可以访问。但是b内部可以访问c。如下面所示,类内访问类内无限制。
复制代码 代码如下:

    class testclass
    {
        public int a = 0;
        private int b = 0;
        protected int c = 0;

pulic  static  int d=0;
        private void os()
        {
            int a1 = a;
            int a2 = b;
            int a3 = c;
        }
    }


b继承之后,c就变为private。也就说b的继承类无法访问c;如下所示,d中无法访问c。
复制代码 代码如下:

    class d : b
    {
        private void st()
        {
            b bo = new b();
            int dd = bo.c;//wrong访问受限制
        }
    }

static修饰符表明该字段或方法是类所有,不是某个具体对象的。testclass类不同实例化时a、b、c的值不同,但d是相同的。如果说a、b、c相当于每个人在哪个省,那么d表明大家都在中国。
复制代码 代码如下:

    class b:testclass
    {
        testclass tec = new testclass();
        int bb = tec.a;//wrong 错误原因是因为字段的初始值引用了非静态字段
        int cc = testclass.d;
        private void st()
        {

            b bo = new b();
            int aa = tec.a;
            int tt = bo.c;
        }
    }

小结:

puclic修饰:类内,类外皆可;private:内部;protect:类内即其派生类。