C# 嵌套类

嵌套类顾名思义就是类或者结构中定义的类
class Container
{
    class Nested
    {
        Nested() { }
    }
}


<1>嵌套类的默认访问权限是private ,可以指定为public,protected,private,internal,protected internal。
<2>嵌套类型可以访问外部类(包裹嵌套类的类),如果要访问外部类型,要把外部类通过构造函数传进一个实例
<3>嵌套类中只能访问外部类中的静态成员,不能直接访问外部类的非静态成员。
namespace ConsoleApplication11Anonymous
{
    class Class1
    {
        private int x;
        protected string str;
        static int y;


        public class Nested
        {
            int xx;
            string ss;
            void print()
            {
                //int y = x;  //error,不能访问外部的非静态成员
                int z = y;    //OK ,可以访问外部的静态成员
            }


            public Nested(Class1 A)
            {
                xx = A.x;   //通过外部类的实例来访问外部类私有成员
                ss = A.str; //通过外部类的实例来访问外部类保护成员
            }
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
           
            Class1 X = new Class1();
            Class1.Nested CN = new Class1.Nested( X );
            


        }


    }
}
<4>根据C#作用域的规则,外部类只能通过内部类的实例来访问内部类的public成员,不能访问protected,private。

class Class2
    {
        private int x;
        static private int y;

        public void func()
        {
            //x = xx;   //当前上下文中不存在名称“xx”
            //x = zz;   //当前上下文中不存在名称“zz”
            //x = aa;   //当前上下文中不存在名称“aa”
            x = Nested.aa;
            Console.WriteLine(x);
        }

        public void funcs()
        {
            //这个只能访问Nested类的public成员
            Nested XX = new Nested();
            x = XX.zz;
            Console.WriteLine(x);
            //x = XX.aa;//访问静态成员只能通过类名而不是实例
            x = Nested.aa;
            Console.WriteLine(x);
        }

        private class Nested
        {
            private int xx;
            protected int yy;
            public int zz;
            public static int aa;
            
        }
    }




  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值