C#中的继承+ NestedClasses [英] Inheritance + NestedClasses in C#

查看:134
本文介绍了C#中的继承+ NestedClasses的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以在C#中使用嵌套类。这些嵌套类也可以继承OuterClass。例如:

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 NestedClass : OuterClass
  {
    // code here
  }
}

是完全可以接受的。

我们也可以在不将NestedClass作为OuterClass的嵌套类的情况下实现这一目的,如下所示:

We can also achieve this without making NestedClass as nested class to OuterClass as below:

public class OuterClass
{
  // code here
}

public class NestedClass : OuterClass
{
  // code here
}

我在想,什么是上述两种情景之间的区别?在方案I中可以实现的是在方案II中无法实现的?通过使NestedClass嵌套到OuterClasss,我们能得到更多的东西吗?

I am wondering, what is the difference between above two scenarioes? What is achievable in scenario I which can't be achievable in scenario II? Is there anything that we get more by making NestedClass "nested" to OuterClasss?

推荐答案

你提供的第二个例子是不是嵌套类,而是源自 OuterClass 的普通类。

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


  • 嵌套类型默认为 private 可见性,但可以声明具有更广泛的可见性

  • 嵌套类型可以访问包含类型的属性,字段和方法(甚至是那些声明为 private 的那些以及从基类型继承的那些)

  • 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)

还要看看这个问题

MSDN链接:嵌套类型(C#编程指南)

EDIT

要解决@Henk关于两种关系(继承与嵌套类型)性质差异的评论:
在这两种情况下,你都有两者之间的关系课程,但他们是不同的性质。从派生类派生时,派生类继承基类的所有(除了 private )方法,属性和字段。嵌套类不适用。嵌套类不会继承任何内容,但可以访问包含类中的所有内容 - 甚至 private 字段,属性和方法。

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.

这篇关于C#中的继承+ NestedClasses的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆