Delphi 中的 const 函数
在我正在查看的 Delphi 代码中,我发现了以下几行:
const
function1: function(const S: String): String = SomeVariable1;
function2: function(const S: String): String = SomeVariable2;
这是做什么的?我的意思是,不是函数中的实际代码,而是在 const 部分中声明函数并将其与变量值进行比较(?)它会做什么?我假设单个等于是一个比较,因为这就是 Delphi 中其他地方的比较。
谢谢。
In the Delphi code I am looking at I've found the following set of lines:
const
function1: function(const S: String): String = SomeVariable1;
function2: function(const S: String): String = SomeVariable2;
What is this doing? I mean, not the actual code within the functions, but what does it do to declare a function inside the const section and compare(?) it with a variable value? I'm assuming the single equals is a comparison since that's what it is everywhere else in Delphi.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,等于是一个赋值,因为这就是常量的赋值方式。例如,考虑一下,
或者
还有“类型化常量”:
在上面的代码片段中,我们定义了一个类型化常量,它包含签名
function(const S: String): String
的函数。我们将(兼容)函数SomeVariable1
分配给它。SomVariable1
必须在代码的前面定义,例如,考虑以下示例:
No, the equals is an assignment, as this is how constants are assigned. Consider, for example,
or
There are also 'typed constants':
In your snippet above, we define a typed constant that holds a function of signature
function(const S: String): String
. And we assign the (compatible) functionSomeVariable1
to it.SomVariable1
has to be defined earlier in the code, for instance, asConsider the following example:
安德烈亚斯的答案很好地涵盖了技术部分,但我想提供这部分的答案:
更多类似
为什么要使用这个看起来很奇怪的构造
?我可以想到两个原因:{$J+}
(可分配的类型常量)编写的,并且“常量”在某些时候被分配了不同的值。如果function1
被声明为变量,则初始化需要在单元的initialization
部分中完成,这可能为时已晚(如果其他单元的>initialization
部分在此之前运行,并尝试调用function1
“函数”)function1
更改为SomeVariable1 并且有无法轻易更改的第 3 方代码。这提供了一种声明别名的单行方法。
Andreas's answer covers the technical bits very well, but I'd like to provide an answer to this part:
More along the lines of
Why use this weired-looking construct
? I can think of two reasons:{$J+}
(assignable typed constants), and the "constant" is assigned a different value at some point. Iffunction1
were declared as a variable, the initialization would need to be done in theinitialization
section of the unit, and that might be too late (if some other unit'sinitialization
section runs before this one and attempts calling thefunction1
"function")function1
toSomeVariable1
and there's 3rd party code that can't easily be changed. This provides a one-line way of declaring the alias.