Delphi中的Const函数

mnu*_*zzo 3 delphi const function delphi-6

在我看到的Delphi代码中,我发现了以下几行:

const
    function1: function(const S: String): String = SomeVariable1;
    function2: function(const S: String): String = SomeVariable2;
Run Code Online (Sandbox Code Playgroud)

这是做什么的?我的意思是,不是函数中的实际代码,而是如何在const部分中声明一个函数并将它(?)与变量值进行比较?我假设单个等于是一个比较,因为这就是Delphi中的其他地方.

谢谢.

And*_*and 18

不,等于是赋值,因为这是常量的赋值方式.例如,考虑一下

const Pi = 3.1415;
Run Code Online (Sandbox Code Playgroud)

要么

const s = 'This is an example';
Run Code Online (Sandbox Code Playgroud)

还有'键入的常量':

const Pi: extended = 3.1415;
Run Code Online (Sandbox Code Playgroud)

在上面的代码片段中,我们定义了一个包含签名函数的类型化常量function(const S: String): String.我们SomeVariable1为它分配(兼容)功能.

SomVariable1 必须在代码的早期定义,例如,

function SomeVariable1(const S: String): String;
begin
  result := S + '!';
end;
Run Code Online (Sandbox Code Playgroud)

请考虑以下示例:

function SomeVariable1(const S: String): String;
begin
  result := S + '!';
end;

const
  function1: function(const S: String): String = SomeVariable1;

procedure TForm1.FormCreate(Sender: TObject);
begin
  caption := function1('test');
end;
Run Code Online (Sandbox Code Playgroud)


Cos*_*und 8

Andreas的答案很好地涵盖了技术方面,但我想提供这个部分的答案:

这是做什么的?

更多的是Why use this weired-looking construct什么?我可以想到两个原因:

  • 代码用{$J+}(可分配的类型常量)编写,"常量"在某一点被赋予不同的值.如果function1声明为变量,则需要initialization在单元的部分中进行初始化,这可能为时已晚(如果某个其他单元的initialization部分在此之前运行并尝试调用function1"函数")
  • 如果函数名称已更改function1SomeVariable1并且存在无法轻松更改的第三方代码,则使用此选项.这提供了一种声明别名的单行方式.