Visibility of nested class constructor

后端 未结 6 886
渐次进展
渐次进展 2021-02-13 18:41

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 allo

6条回答
  •  有刺的猬
    2021-02-13 19:15

    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();
        }
    }
    

提交回复
热议问题