嵌套类构造函数的可见性 [英] Visibility of nested class constructor

查看:136
本文介绍了嵌套类构造函数的可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法限制在C#中嵌套类的实例化?我想防止嵌套类从除嵌套类之外的任何其他类中实例化,但允许从其他代码完全访问嵌套类。

Is there a way to limit the instantiation of the nested class in C#? I want to prevent nested class being instantiated from any other class except the nesting class, but to allow full access to the nested class from other code.

推荐答案

通常我为你想暴露给其他类的功能创建一个接口,然后使嵌套类私有并实现该接口。这种嵌套类定义可以保持隐藏:

Usually I create an interface for the functionality you want to expose to other classes, then make the nested class private and implement that interface. This way the nested class definition can stay hidden:

public class Outer
{
    private class Nested : IFace
    {
        public Nested(...)
        {
        }
        //interface member implementations...
    }

    public IFace GetNested()
    {
        return new Nested();
    }
}

这篇关于嵌套类构造函数的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆