停止在Delphi中被重写的功能

时间:2020-03-06 15:04:45  来源:igfitidea点击:

如何阻止超类中的函数/过程在Delphi(2007)的子类中被重写?

我想标记它以便不能更改,我相信这里有一个最终关键字,但是我一生无法找到它的文档,因此我不确定100%就是我所需要的。

解决方案

正如我们所想,关键字为"最终"。参见http://dn.codegear.com/article/34324和http://blogs.teamb.com/rudyvelthuis/2005/05/13/4311. 另外,我们可以将类标记为密封的,以防止任何人从其继承。我们需要的Delphi版本高于7.

type
  TSomeClass = class
  protected
    procedure SomeVirtualMethod; virtual;
  end;

  TOtherClass = class(TSomeClass)
  protected
    procedure SomeVirtualMethod; override; final;
  end;

我们是对的,这是"最终的"。此代码段显示了它。 (摘自Marco Cantu的其中一本书)

type
  TDeriv1 = class (TBase)
    procedure A; override; final;
  end;

  TDeriv2 = class (TDeriv1)
    procedure A; override; // error: "cannot override a final method"
  end;

编译给出:

[Pascal Error] Unit1.pas(11): E2352 Cannot override a final method

让我惊讶的一件事:Win32 Delphi中支持此功能,而不仅仅是.NET的Delphi。