What's the difference between a public constructor in an internal class and an internal constructor?

前端 未结 5 1648
礼貌的吻别
礼貌的吻别 2020-12-03 04:16

I have an internal class, an internal constructor won\'t allow it to be used in a generic collection so I changed it to public. What\'s the accessibility if you have a publi

5条回答
  •  青春惊慌失措
    2020-12-03 04:48

    A public class with an internal constructor can still be used by outside code, if you return an object of that class from a public function.

    Outside code then has access to that object, but still can not create a new one.

    Assembly 1:
    
    public class Exclusive
    {
      internal Exclusive() {}
      public void DoSomething() {}
    }
    
    public class Factory
    {
      public Exclusive GetExclusive() { return new Exclusive(); }
    }
    
    Assembly 2:
    
    Factory MyFactory = new Factory();
    Exclusive MyExclusive = MyFactory.GetExclusive(); // Object is created in Assembly 1
    MyExclusive.DoSomething();
    
    Exclusive MyExclusive = new Exclusive(); // Error: constructor is internal
    

    Whereas an internal class can not be used outside the assembly at all:

    Assembly 1:
    
    internal class Exclusive
    {
      public Exclusive() {}
      public void DoSomething() {}
    }
    
    public class Factory
    {
      public Exclusive GetExclusive() { return new Exclusive(); }
    }
    
    Assembly 2:
    
    Factory MyFactory = new Factory();
    Exclusive MyExclusive = MyFactory.GetExclusive(); // Error: class Exclusive not found
    

提交回复
热议问题