Nested types

因为是基础,所以一定要吃透,记牢。归整一下,方便记忆。

A type defined within a class or struct is called a nested type. For example:

class Container
{
   
class Nested
    {
        Nested() { }
    }
}

//class 里面可以定义 class and struct

//struct 里面也可以定义 class and struct 

Regardless of whether the outer types is a class or a struct, nested types default to private, but can be made public, protected internal, protected, internal, or private. In the previous example, Nested is inaccessible to external types, but can be made public like this:

class Container
{
    public class Nested
    {
        Nested() { }
    }
}

// class and struct里面的所有成员默认是private

// 但是所有的nested type默认都是private

// nested type可以有5种访问修饰符

// 非nested type 只能有两种修饰符 internal and public

// nested type 可以被包含类访问,但不可以被外部的类访问

// nested type 可以访问外部类和包含类

The nested, or inner type can access the containing, or outer type. To access the containing type, pass it as a constructor to the nested type. For example:

public class Container
{
    public class Nested
    {
        private Container parent;

        public Nested()
        {
        }
        public Nested(Container parent)
        {
            this.parent = parent;
        }
    }
}

//Nested types 可以访问包含类的私有和保护成员,包括继承过来的私有和保护成员。

Nested types can access private and protected members of the containing type, including any inherited private or protected members.

In the previous declaration, the full name of class Nested is Container.Nested. This is the name used to create a new instance of the nested class, as follows:

Container.Nested nest = new Container.Nested();

 

//the accessibility domain of a nested type cannot exceed that of the containing type.

 

//疑惑:在Nested types中也可以new一个包含类的实例,这样不会造死循环吗?

class MyClass1
{
    public int j = 2;
    class MyInternalClass
    {
        MyClass1 x1 = new MyClass1();
        public void func()
        {
            Console.WriteLine(x1.j);
        }
    }
}

参考:

http://msdn.microsoft.com/en-us/library/ms229027.aspx

http://msdn.microsoft.com/en-us/library/tdz1bea9(VS.71).aspx

http://msdn.microsoft.com/en-us/library/ms173120.aspx 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值