浅谈C#类成员的访问属性

1.public

public属性的成员,访问不受限,容易理解,不必多说;

2.protected

protected属性的成员,访问仅限于此类和从此类派生的类;

3.private

private属性的成员,访问仅限于此类访问;

4.internal

internal属性的成员,访问仅限于此程序;

着重区分一下protected和private两者,举例来说:

    class BaseTest
    {
        public int a = 1;
        protected int b = 2;
        internal int aa = 3;
        private int bb = 4;

        public void print()
        {
            BaseTest test = new BaseTest();
            Console.WriteLine("Print Member a : {0} , b : {1} , aa : {2} , bb : {3}", test.a, test.b, test.aa, test.bb); // 此处可正确访问
        }
    }

    class Program:BaseTest
    {
        public int c;
        public int d;
        public int cc;
        public int dd;

        public void init()
        {
            BaseTest bstest = new BaseTest();
            this.c = bstest.a;
            this.d = bstest.b;  // 此处会发生报错,基类对象无法访问基类protected成员b
        }

        static void Main(string[] args)
        {
            Program pm = new Program();
            BaseTest bstest = new BaseTest();
            pm.c = bstest.a;
            pm.d = bstest.b;  // 此处发生报错,提示错误同上
            pm.d = pm.b;       // 此处可正确访问
            pm.cc = bstest.bb;  // 此处发生报错,基类private成员bb不可访问
        }
    }

如上代码中所示,protected成员只能在基类中(此处与private成员受限及其相似)、或者派生类中通过派生类对象进行访问。

没有更多推荐了,返回首页