嵌套类型(C# 编程指南)Nested Types (C# Programming Guide)

构造中定义的类型称为嵌套类型。A type defined within a class or struct is called a nested type. 例如:For example:

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

不论外部类型是类还是构造,嵌套类型均默认为 private;仅可从其包含类型中进行访问。Regardless of whether the outer type is a class or a struct, nested types default to private; they are accessible only from their containing type. 在上一个示例中,Nested 类无法访问外部类型。In the previous example, the Nested class is inaccessible to external types.

还可指定访问修饰符来定义嵌套类型的可访问性,如下所示:You can also specify an access modifier to define the accessibility of a nested type, as follows:

以下示例使 Nested 类为 public:The following example makes the Nested class public:

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

嵌套类型(或内部类型)可访问包含类型(或外部类型)。The nested, or inner, type can access the containing, or outer, type. 若要访问包含类型,请将其作为参数传递给嵌套类型的构造函数。To access the containing type, pass it as an argument to the constructor of the nested type. 例如:For example:

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

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

嵌套类型可以访问其包含类型可以访问的所有成员。A nested type has access to all of the members that are accessible to its containing type. 它可以访问包含类型的私有成员和受保护成员(包括所有继承的受保护成员)。It can access private and protected members of the containing type, including any inherited protected members.

在前面的声明中,类 Nested 的完整名称为 Container.NestedIn 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();

请参阅See also