加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:36:28 所属栏目:百科 来源:网络整理
导读:我想要定义容器类和外部类可访问的嵌套类,但我想控制嵌套类的实例化,这样只有容器类的实例才能创建嵌套类的新实例. 诉讼代码应该有希望证明这一点: public class Container{ public class Nested { public Nested() { } } public Nested CreateNested() { r
我想要定义容器类和外部类可访问的嵌套类,但我想控制嵌套类的实例化,这样只有容器类的实例才能创建嵌套类的新实例.

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

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

    }
}

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

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

解决方法

如何通过接口进行抽象?
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

    }
}

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

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

    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读