嵌套类构造函数的可见性

Bog*_*ogi 11 c# constructor visibility nested-class

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

Lee*_*Lee 27

通常我会为您要向其他类公开的功能创建一个接口,然后使嵌套类成为私有并实现该接口.这样,嵌套类定义可以保持隐藏状态:

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

    public IFace GetNested()
    {
        return new Nested();
    }
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*ert 6

总之,不,你不能那样做.有一个accessibity修饰符"public",意思是"可以通过我内部或我之外的任何东西访问",并且有一个可访问性修饰符"private",意思是"可以通过我内部的任何东西访问".没有修饰符意味着"可以访问我外面的东西但不能访问它之外的任何东西",这就是你需要将构造函数标记为.这根本不是类型系统设计者认为有用的概念.

你能描述为什么你想要这种疯狂的可访问性吗?也许有更好的方法来获得你想要的东西.

  • @MatteoSp:虽然我觉得你认为我对我实现的功能有误,但我确信我说我的说法是正确的,因为没有适合原始海报描述的描述的可访问性修饰符. (7认同)

Suz*_*ron 6

如果您需要满足以下要求之一:

  • 您希望密封嵌套类,
  • 您不希望将所有嵌套类的方法签名复制到Lee的答案中的接口,

我找到了类似于ak99372发布的解决方案,但没有使用静态初始化器:

public class Outer
{
    private interface IPrivateFactory<T>
    {
        T CreateInstance();
    }

    public sealed class Nested
    {
        private Nested() {
            // private constructor, accessible only to the class Factory.
        }

        public class Factory : IPrivateFactory<Nested>
        {
            Nested IPrivateFactory<Nested>.CreateInstance() { return new Nested(); }
        }
    }

    public Nested GetNested() {
        // We couldn't write these lines outside of the `Outer` class.
        IPrivateFactory<Nested> factory = new Nested.Factory();
        return factory.CreateInstance();
    }
}
Run Code Online (Sandbox Code Playgroud)

这个想法是Nested类的构造函数只能被Factory类更容易地嵌入.本Factory类明确地实现该方法CreateInstance从私有接口IPrivateFactory,因此,只有那些谁可以看到IPrivateFactory可以打电话CreateInstance,并得到一个新的实例Nested.

Outer类之外的代码无法自由创建实例而Nested不会询问Outer.GetNested(),因为

  1. Outer.Nested的构造函数是私有的,所以他们不能直接调用它
  2. Outer.Nested.Factory可以实例化,但不能强制转换IPrivateFactory,因此CreateInstance()无法调用其方法.

请注意,我不建议在生产代码中大量使用该模式,但这是一个技巧,我发现在极少数情况下可以使用它.