Allow access to but prevent instantiation of a nested class by external classes

后端 未结 2 1867
遇见更好的自我
遇见更好的自我 2021-01-05 01:10

I\'m looking to define a nested class that is accessible to the container class and external classes, but I want to control instantiation of the nested class, such that only

相关标签:
2条回答
  • 2021-01-05 01:43

    How about abstraction via an interface?

    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
    
        }
    }
    

    You can also do the same thing with an abstract base-class:

    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
    
        }
    }
    
    0 讨论(0)
  • 2021-01-05 01:56

    It is impossible to declare class in such way. I think that the best way for you would be to declare class as private and expose it through public interface:

    class Program
    {
        static void Main(string[] args)
        {
           // new S.N(); does not work
            var n = new S().Create();
        }
    }
    
    class S
    {
        public interface IN
        {
            int MyProperty { get; set; }
        }
        class N : IN
        {
            public int MyProperty { get; set; }
            public N()
            {
    
            }
        }
    
        public IN Create()
        {
            return new N();
        }
    }
    
    0 讨论(0)
提交回复
热议问题