是否可以在 Delphi 和 FreePascal 中声明数组的 const 而不让元素为常量?
很久以前,我记得我可以在 Turbo Pascal 7 中做到这一点。
也许我错了,这是我需要澄清的事情,但是是否可以将字符串数组声明为常量?
如果不是,有什么选项/解决方法。
我现在拥有的是:
type
TStates = (sOne, sTwo, sThree);
var
TArrayOfString: array [sOne..sThree] of string =
('State one', 'State two', 'State three');
但想用 const 替换该 var。
谢谢
编辑1:添加了更多代码来澄清我的问题。
A long time ago I remember I could do this in Turbo Pascal 7.
Maybe I'm wrong and it's something I need to clarify, but is it possible to declare an array of strings as a constant?
If not what's the option/workaround.
What I have now is:
type
TStates = (sOne, sTwo, sThree);
var
TArrayOfString: array [sOne..sThree] of string =
('State one', 'State two', 'State three');
but would want to replace that var with a const.
Thanks
Edit 1: Added some more code to clarify my question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需将 var 替换为 const 是完全合法的:
我很好奇为什么你的标识符名称以 T 开头。 您是否尝试定义这样的类型:
您不能将可变长度数组(AFAIK)作为 const,也不能将其设为未定义的类型。
这是使用 Delphi 2009。YMMV 和 FreePascal。
Just replacing var with const is perfectly legal:
I am curious why your identifier name starts with a T though. Were you trying to define a type like this:
You cannot have a variable length array (AFAIK) as a const, nor can you have it of an undefined type.
This is with Delphi 2009. YMMV with FreePascal.
在过去的 pascal/delphi 中,当您写道:
您没有定义常量,而是定义了初始化变量。
您可以毫无问题地定义:
但字符串也必须是常量。 它们需要在编译时就知道。
同样的情况也适用:
所以你不能写:
因为 B 是一个 var。 但你可以这样写:
请注意,提供了选项:“可分配类型常量”(默认为 false)来创建可以分配的旧时间类型常量。 它只是为了向后兼容,因为您确实希望常量保持不变。
In old day pascal/delphi when you wrote:
You did not define a constant, but an initialized variable.
You can define without problem:
But the strings have to be constants too. They need to be known at compile time.
The same goes for:
So you can't write:
Because B is a var. But you can write:
Note that the option: "Assignable typed constants" (default false) is provided to create the old time typed constants that can be assigned. It is just there for backwards compatibility, because you really want your constants to be constant.