zoukankan      html  css  js  c++  java
  • 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;
                
            }
        }
  • 相关阅读:
    记一次网易前端实习面试
    你知道吗?Web的26项基本概念和技术
    CSS 颜色代码大全
    研究旧项目, 常用 sql 语句
    Asp.net core 学习笔记 QR code and Barcode
    Html to PDF
    Asp.net core 学习笔记 Node Service
    Asp.net core Identity + identity server + angular + odata + 权限管理
    Angular Material (Components Cdk) 学习笔记 Table
    es6 getter setter
  • 原文地址:https://www.cnblogs.com/kanekiken/p/7554802.html
Copyright © 2011-2022 走看看