Inheritance + NestedClasses in C#

后端 未结 4 529
心在旅途
心在旅途 2020-12-17 21:25

We can have nested classes in C#. These nested classes can inherit the OuterClass as well. For ex:

public class OuterClass
{
  // code here
  public class Ne         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 22:00

    the second example you provided is not a nested class, but a normal class that derives from OuterClass.

    • nested types default to private visibility, but can be declared with a wider visibility
    • nested types can access properties, fields and methods of the containing type (even those declared private and those inherited from base types)

    also take a look at this question here on when and why to use nested classes.
    MSDN link : Nested Types (C# Programming Guide)

    EDIT
    To address @Henk's comment about the difference in nature of the both relations (inheritance vs. nested types): In both cases you have a relation between the two classes, but they are of a different nature. When deriving from a base class the derived class inherits all (except private) methods, properties and fields of the base class. This is not true for nested class. Nested classes don't inherit anything, but have access to everything in the containing class - even private fields, properties and methods.

提交回复
热议问题