Nested types

经国安
2023-12-01

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

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 

 类似资料:

相关阅读

相关文章

相关问答