newslot 属性的目的是什么?

What is the purpose of newslot attribute?

我正在通过通用语言基础设施这本书学习中级语言。 它声明类型的虚方法可以用 newslot 属性标记。但是那个属性真的让我很困惑,我无法理解它的含义。

引用如下:

II.10.3 - Introducting and overriding virtual methods

A virtual method of a base type is overridden by providing a direct implementation of the method (using a method definition, see §II.15.4) and not specifying it to be newslot (§II.15.4.2.3). An existing method body can also be used to implement a given virtual declaration using the .override directive (§II.10.3.2).

II.10.3.1 Introducing a virtual method

A virtual method is introduced in the inheritance hierarchy by defining a virtual method (§II.15.4). The definition can be marked newslot to always create a new virtual method for the defining class and any classes derived from it:

1) If the definition is marked newslot, the definition always creates a new virtual method, even if a base class provides a matching virtual method. A reference to the virtual method via the class containing the method definition, or via a class derived from that class, refers to the new definition (unless hidden by a newslot definition in a derived class). Any reference to the virtual method not via the class containing the method definition, nor via its derived classes, refers to the original definition.

2) If the definition is not marked newslot, the definition creates a new virtual method only if there is not virtual method of the same name and signature inherited from a base class.

It follows that when a virtual method is marked newslot, its introduction will not affect any existing references to matching virtual methods in its base classes.

短语"definition creates a new virtual method"是什么意思?我认为引入虚方法总是会创建新方法。我认为 newslot 是无用的属性。任何人都可以提供示例来阐明该文本吗?

您熟悉 C# 中方法定义中的 new modifier 吗? - 相同的概念。

你说的是 "this method is not the same as any method that my base class exposes, either now or in the future"。即使我们使用了完全相同的名称。人们通过我的基础 class 的变量调用方法 X 或在我的继承链上更远的地方从我的基础 class 获取方法 X。人们在我的 class 或从它派生的 classes 的变量上调用方法 X 得到 this 方法 X(除非派生的 classes 引入他们自己的newslotX方法)

这里的关键是,在 IL 级别,如果有可覆盖的方法可用,覆盖是假定的默认值:

If the definition is not marked newslot, the definition creates a new virtual method only if there is not virtual method of the same name and signature inherited from a base class.

在 IL 级别,您可以将覆盖标记为 virtual,而在 C# 中则不能。这就是为什么 newslot 是重要的区别特征。