德尔福:所有常数都是常数,但有些常数比其他常数更常数? [英] Delphi: All constants are constant, but some are more constant than others?
问题描述
考虑:
const
clHotlight: TColor = $00FF9933;
clLink = clHotLight; //alias of clHotlight
[Error] file.pas: Constant expression expected
以及有效的替代措辞:
const
clHotlight = TColor($00FF9933);
clLink = clHotLight; //alias of clHotlight
解释一下.
然后考虑:
const
AdministratorGUID: TGUID = '{DE44EEA0-6712-11D4-ADD4-0006295717DA}';
SuperuserGUID = AdministratorGUID; //alias of AdministratorGUID
[Error] file.pas: Constant expression expected
并修复.
在声明前添加关键字const
;有人不相信他们是常量.
Added keyword const
before declarations; someone didn't believe they were const.
推荐答案
clHotlight: TColor = $00FF9933;
不是常量而是类型常量(=静态变量),即编译器保留了一个在内存中插入 TColor 的插槽,该 TColor 将在运行时最初保存值 $00FF9933
.
因为该值可以稍后更改(使用可分配常量选项打开),它不是真正的常量,并且不能被编译器在 clLink = clHotLight;
clHotlight: TColor = $00FF9933;
is not a constant but a typed constant (=static variable), i.e. the compiler reserves a slot in memory for a TColor which will hold the value $00FF9933
initially at run time.
Because that value can be changed later (with the Assignable Const option ON), it is not a real constant and cannot be accepted by the compiler in clLink = clHotLight;
clHotlight = TColor($00FF9933);
与 clHotlight = $00FF9933;
它是一个真正的常量,编译器会用它的值 $00FF9933
替换 clHotlight
出现在代码中的任何地方.对于 clLink
也是如此.
clHotlight = TColor($00FF9933);
is strictly the same as clHotlight = $00FF9933;
It is a true constant and the compiler will replace clHotlight
by its value $00FF9933
wherever it appears in the code. And for clLink
as well.
阅读这个 SO 问题(在 Delphi 7 中,为什么我可以为常量赋值?) 以及那里所有的好答案...
Read on this SO question (In Delphi 7, why can I assign a value to a const?) and all the good answers there...
关于 TGUID...
问题是写 AdministratorGUID: TGUID = '{DE44EEA0-6712-11D4-ADD4-0006295717DA}';
是不正确的.
它在幕后使用一些编译器魔法来调用StringToGUID
,从而方便地将GUID表示为一个字符串,而不是它们本质上的字符串.它们是记录.
about TGUID...
The problem is that writing AdministratorGUID: TGUID = '{DE44EEA0-6712-11D4-ADD4-0006295717DA}';
is not proper.
It is using some compiler magic to call StringToGUID
behind the scene, allowing the convenience to express the GUID as a string which they are not by nature. They are records.
因此,尝试 AdministratorGUID = '{DE44EEA0-6712-11D4-ADD4-0006295717DA}';
将不起作用.那不是 GUID...
So, trying AdministratorGUID = '{DE44EEA0-6712-11D4-ADD4-0006295717DA}';
will not work. That is not a GUID...
一种解决方法是使用absolute
让类型常量和变量指向相同的内存区域指令:
A workaround is to have a typed constant and variables pointing to the same memory area using the absolute
directive:
const
AdministratorGUID: TGUID = '{DE44EEA0-6712-11D4-ADD4-0006295717DA}';
var
SuperuserGUID: TGUID absolute AdministratorGUID; //alias of AdministratorGUID
RootGUID: TGUID absolute AdministratorGUID; //alias of AdministratorGUID
这篇关于德尔福:所有常数都是常数,但有些常数比其他常数更常数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!