允许访问但阻止外部类实例化嵌套类

Dan*_*ens 7 c# encapsulation nested-class inner-classes

我想要定义容器类和外部类可访问的嵌套类,但我想控制嵌套类的实例化,这样只有容器类的实例才能创建嵌套类的新实例.

诉讼代码应该有希望证明这一点:

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

    public Nested CreateNested()
    {
        return new Nested();  // Allow
    }
}

class External
{
    static void Main(string[] args)
    {
        Container containerObj = new Container();
        Container.Nested nestedObj;

        nestedObj = new Container.Nested();       // Prevent
        nestedObj = containerObj.CreateNested();  // Allow

    }
}
Run Code Online (Sandbox Code Playgroud)

Nested必须是公开的,以便可以访问它External.我尝试使用Nested受保护的构造函数,但是这会阻止Container创建实例,因为Container它不是基类Nested.我可以将构造函数设置为Nestedto internal,但我希望阻止所有外部类(包括同一程序集中的那些外部类)访问构造函数.有没有办法做到这一点?

如果这不能通过访问修饰符实现,我想知道我是否可以在其中抛出异常Nested().但是,我不知道如何测试new Nested()调用的上下文.

Mar*_*ell 10

如何通过接口进行抽象?

public class Container
{
    public interface INested
    {
        /* members here */
    }
    private class Nested : INested
    {
        public Nested() { }
    }

    public INested CreateNested()
    {
        return new Nested();  // Allow
    }
}

class External
{
    static void Main(string[] args)
    {
        Container containerObj = new Container();
        Container.INested nestedObj;

        nestedObj = new Container.Nested();       // Prevent
        nestedObj = containerObj.CreateNested();  // Allow

    }
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用抽象基类执行相同的操作:

public class Container
{
    public abstract class Nested { }
    private class NestedImpl : Nested { }
    public Nested CreateNested()
    {
        return new NestedImpl();  // Allow
    }
}

class External
{
    static void Main(string[] args)
    {
        Container containerObj = new Container();
        Container.Nested nestedObj;

        nestedObj = new Container.Nested();       // Prevent
        nestedObj = containerObj.CreateNested();  // Allow

    }
}
Run Code Online (Sandbox Code Playgroud)