开发者

public inner classes

Can anyone explain, why we can 开发者_开发技巧do such thing and why we need this

public class OuterClass
{
  public class InnerClass 
  {
  }
}

Why we need public inner whatever: struct, class, enum or static class?

I think that if it is inner then it must be only private or protected.


You don't generally need public nested types - but they can be useful sometimes. They make it very clear that one type is explicitly associated with another.

They also allow the nested type to access the private members of the enclosing type (in C#), which may be useful at times. I would guess that List<T>.Enumerator may do that, for example. In Java the access rules work the other way round - the enclosing class has access to the private members of the nested classes.

I think would have to explain why you'd want to explicitly prohibit this rather than why it's needed, as such. I can't think of anywhere else that you can specify an access modifier but can't make it public, other than for inconsistency (declaring a public method with an internal return type, for example).


Public inner types are generally not recommended, see this reference http://msdn.microsoft.com/en-us/library/tdz1bea9(v=VS.71).aspx

...but since there are (may be) exceptions, this is still allowed


Consider this example:

public class TrainingFile {

    public List<TrainingFileEntry> getEntries() {
           return ...
    }

    public class TrainingFileEntry {
        int x;
        int y;
   }
}

You want to hide the details of the TrainingFileEntry, but your customer needs to be able to use it. Ofc you could create an own file for this nested class, but such a nested helper class ist mostly not a "standalone" and stuck to the class where it is nested. -)


Its very useful when every member of InnerClass really does belong to one, and only one member of outer class. I have used that construct where OuterClass was a collection of mathematical objects and InnerClass was the actual objects themselves.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜