System.Object是基类

对于许多人来说,这个问题可能是常见的,我试了一个小时来理解这些事情,但没有得到适当的解释。

MSDN说, System.Object是.NET Framework中所有类的最终基类; 它是类型层次结构的根。

当C#不允许多重inheritance时,我怎样才能inheritance,比如A类到B类。 因为所有类,都已经从System.Objectinheritance了吗? 我在这里谈论正常的inheritance。

Class A { --- } Class B : A { --- } 

请清除我的怀疑。 谢谢。

更新:

同样,我怀疑的是,所有类inheritance自System.Object,然后使类B具有类A和System.Object。 从我上面的例子

正确,C#只允许单一inheritance。 System.Object类由类A隐式inheritance。因此,类B是-A A,它是一个System.Object。 这由编译器负责,因此您不需要明确说出Class A : System.Object (尽管您可以,如果您愿意)。

很容易。 猿遗传自动物,黑猩猩inheritance自猿。 黑猩猩也从动物身上inheritance,但主要不是通过猿。 在.NET中,如果类没有显式声明其inheritance,则编译器会添加IL代码以从System.Objectinheritance它。 如果是,则通过父类型inheritanceSystem.Object。

看,你只能有一个父亲。 但你的父亲也可以有一个父亲。 因此,您从祖父那里inheritance了一些属性。 Dog类inheritance自Mammals ,而Mammalsinheritance自Animal类,而Animal类又inheritance自LivingThing类。

多重inheritance意味着例如A类直接从B类和C类inheritance,如下所示:

 class A : B, C 

这在C#中不起作用 。 您的示例意味着您从一个本身inheritance自另一个的类inheritance,如下所示:

 class A : object { } class B : A { } 

这在C#中是可能的。

好像你对“多重inheritance”的含义有些轻微的混淆?

当’Binheritance自A,而Ainheritance自O’时, 不会发生多重inheritance。 这只是一个简单的inheritance层次结构 – 这是C ++,Java和C#的一个特性。

在上面的例子中,我们假设B 直接从Ainheritance,并间接从Oinheritance.B从Ainheritance(非私有)成员,间接从O(非私有)成员inheritance。

C ++另外支持真正的多重inheritance,有时可称为“混合inheritance”:多重inheritance的一个例子是

  class A : public O {}; class B : A, O {}; 

这里B直接从Oinheritance, 直接从Ainheritance – 在这种情况下,B的两个 O成员副本存在,为了访问来自O的B成员,你需要指定你想要的那些副本:

例如bO::omember; 或者bA::omember;

使用大型C ++类框架时,在使用多重inheritance时,通常可以在派生类中获得不需要的基类副本。 为了解决这个问题,C ++提供了虚拟inheritance ,它只强制inheritance虚拟基类的一个副本:下面的例子应该清楚这一点(或者让它更加混乱!)

 // Note, a struct in C++ is simply a class with everything public struct O { int omember; }; struct A1 : O {}; struct B1 : O, A1 {}; struct A2 : virtual O {}; struct B2 : virtual O, A2 {}; B1 b1; B2 b2; // There are two 'omember's in b1 b1.omember; // Compiler error - ambiguous b1.A1::omember = 1; b1.O::omember = 2; // There's only one 'omember' in b2, so all the following three lines // all set the same member b2.A2::omember = 1; b2.O::omember = 2; b2.omember = 3; 

A类inheritance自System.Object。 B类inheritance自A类,它inheritance自System.Object

您不能inheritance两个类,但可以inheritance类的层次结构。

 System.Object | \-- Class A {} | \-- Class B {} public class ClassA { } public class ClassB : ClassA { } public class ClassC : ClassB { } 

多重inheritance意味着从多个类inheritance到一个类中。 您的示例有效,但您无法执行以下操作:

B级:A,C {—}

多重inheritance的定义:

“多重inheritance是一些面向对象的计算机编程语言的一个特性,其中一个类可以从多个超类inheritance行为和特性。”