Is it possible to have a private class?

前端 未结 4 1249
隐瞒了意图╮
隐瞒了意图╮ 2021-01-12 13:40

I always wonder if it is possible to have a private class? And, what would be the point of having such class?

Thanks for helping.

相关标签:
4条回答
  • 2021-01-12 13:54

    Yes it is possible to have a private class, but only as an inner class of another class:

    public class Outer
    {
        private class Inner
        {}
    }
    

    This is usually useful when you want to encapsulate some logic inside of a class (the outer one), but need a more structured/OO design of code to implement it. I have used this pattern in the past when I need a container class to process some information within a method of a class, but the container class has no meaning outside of this logic. Making the container class a private inner class means that its use is localised to the outer class that utilises it.

    It is worth noting that with this structure, the inner class has access to the private members of the outer class, but not the other way around.

    0 讨论(0)
  • 2021-01-12 14:02

    Having private non-nested classes (Visible only to their namespace and child namespaces only) would allow to clean code boundaries while programming in the same assembly.

    Having for example only an interface and a factory visible from other namespaces in the same assembly while still having all the implementation of the interface and utility classes (that no-one have business knowing out of the namespace) there.

    It is still possible to do it somewhat with a big partial class replacing a namespace and nested classes inside but it's a very bad hack and unit testing become nearly impossible.

    0 讨论(0)
  • 2021-01-12 14:03

    Yes you can - usually they are nested classes inside another type. This means you can aggregate logic into a nested class without exposing the class to anything else. Internal is also useful for nested classes.

    Note however that there are some arguments against a design requiring nested classes - I tend to use them when they seem a good fit though.

    0 讨论(0)
  • 2021-01-12 14:10

    You can have a private class, inside another class.

    You may use a private class to encapsulate logic and implementation. For example you can declare an implementation of an iterator in your implementation of ICollection.

    0 讨论(0)
提交回复
热议问题