C# System.Object 是终极基础 class

C# System.Object being the ultimate base class

在 msdn 规范中,我注意到 System.Object 是 .Net 中的最终基础 class。 他们说 System.ValueType 是一个抽象 class 继承自 System.Object 并覆盖 EqualsCompare 等方法... boolint 等值类型继承自 System.ValueType 所有其他 .net 对象继承自 System.Object.

我有 2 个问题。

  1. System.Object需要什么?为什么这里没有首选界面?

我假设它只有 2 个直接子节点(忽略我们可以创建更多),即 System.ValueType 和 System.ReferenceType 两者都有完全不同的实现。

**编辑:**没有 System.ReferenceType。只有 Sytem.Object 和 Sytem.ValueType(覆盖基础 class)。 在这里道歉。

所以可能需要 System.Object 来处理基本的 CLR 功能,例如使用 new() 创建对象、强制执行默认构造函数、GC 等?

  1. 当我反编译 Sytem dll 并查看 bool 的实现时,我只看到一个结构。
    对于 class(比如异常)我没有查看对 System.ReferenceType 或 System.Object 的继承。这种继承是如何处理的?
    事实上,Common Type System 对 MyCustomClass 做了什么以使其继承自 System.Object(因为继承是在编译时确定的,我认为 CTS 正在这样做)

如果我的理解有误,请随时纠正me/edit post。

你这个问题有很多问题。以后考虑每个问题发一个问题。

What is the need of System.Object?

问题含糊不清。让我改一下。

Why was the C# type system designed so that all non-pointer types had a common base type?

获得多态性的好处。在没有泛型的类型系统中,例如 C# 1.0 类型系统,您希望能够创建任意对象的列表。

Why wasn't an interface preferred over a class type?

接口指定功能。 Base classes 允许共享实现。 Object 上的方法具有在派生类型之间共享的实现。

Am assuming it has only 2 direct Children(ignoring that we can create more) which is System.ValueType and System.ReferenceType both having entirely different implementations.

这完全是错误的。

So System.Object may be needed to handle the basic CLR functionalities like object creation using new()

没有

enforcing default constructor

没有。尽管最终调用了对象的默认构造函数是真的,但该构造函数不执行任何操作。所以说类型的目的是保证一个什么都不做的构造函数被调用,说起来很奇怪。

GC etc ?

没有

When I de-compile System.dll, and see the implementation of bool, I just see a struct.

正确。您应该知道所有不可为 null 的非枚举结构都直接继承自 System.ValueType.

For a class (say Exception) I don't see the inheritance to System.ReferenceType or System.Object.

正确。您应该知道所有 class 类型都继承自 System.Object(当然,如果没有指定其他类型。)

How is this inheritance handled ?

问题太模糊,无法回答。

what is Common Type System doing to MyCustomClass to make it inherit from System.Object(since the inheritance is determined at compile time am thinking CTS is doing it)

我完全不知道你想问什么。尝试使问题更精确。

一个你没有问但可能应该问的问题是:

What does it mean when I say that type A inherits from type B?

表示所有类型B的成员也是类型A的成员

All members? Even private members?

是的。继承是属性一种类型的成员也是另一种类型的成员。