delphi 常量数组_如何在Delphi中声明和初始化常量数组

在Delphi编程中,常量数组是一种只读的数组,其值在声明时必须初始化。本文提供了三个示例,展示了如何声明和初始化字符串、布尔类型和自定义记录类型的常量数组。示例包括一个包含一周天数的字符串数组,一个用于设置屏幕光标的布尔数组,以及一个存储TShopItem记录的数组。尝试修改常量数组的值会导致编译错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

delphi 常量数组

In Delphi, the versatile web-programming language, arrays allow a developer to refer to a series of variables by the same name and to use a number—an index—to tell them apart.

在通用的Web编程语言Delphi中, 数组允许开发人员使用相同的名称引用一系列变量,并使用数字(索引)来区分它们。

In most scenarios, you declare an array as a variable, which allows for array elements to be changed at run-time.

在大多数情况下,您将数组声明为变量,这允许在运行时更改数组元素。

However, sometimes you need to declare a constant array—a read-only array. You cannot change the value of a constant or a read-only variable. Therefore, while declaring a constant array, you must also initialize it.

但是,有时您需要声明一个常量数组-一个只读数组。 您不能更改常量或只读变量的值。 因此,在声明常量数组的同时 ,还必须对其进行初始化。

三个常量数组的示例声明 ( Example Declaration of Three Constant Arrays )

This code example declares and initializes three constant arrays, named Days, CursorMode, and Items.

此代码示例声明并初始化三个名为DaysCursorModeItems的常量数组。

  • Days is a string array of six elements. Days[1] returns the Mon string.

    是由六个元素组成的字符串数组。 Days [1]返回Mon字符串。

  • CursorMode is an array of two elements, whereby declaration CursorMode[false] = crHourGlass and CursorMode = crSQLWait. "cr*" constants can be used to change the current screen cursor.

    CursorMode两个元素组成数组 ,其中声明CursorMode [false] = crHourGlass和CursorMode = crSQLWait。 “ cr *”常量可用于更改当前屏幕光标。

  • Items defines an array of three TShopItem records.

    Items定义了三个TShopItem 记录的数组。


type
   TShopItem = record
     Name : string;
     Price : currency;
   end;
const
   Days : array[0..6] of string =
   (
     'Sun', 'Mon', 'Tue', 'Wed',
     'Thu', 'Fri', 'Sat'
   ) ;
   CursorMode : array[boolean] of TCursor =
   (
     crHourGlass, crSQLWait
   ) ;
   Items : array[1..3] of TShopItem =
   (
     (Name : 'Clock'; Price : 20.99),
     (Name : 'Pencil'; Price : 15.75),
     (Name : 'Board'; Price : 42.96)
   ) ;

Trying to assign a value for an item in a constant array raises the "Left side cannot be assigned to" compile time error. For example, the following code does not successfully execute:

尝试为常量数组中的项目分配值会导致“无法分配左侧”的编译时间错误。 例如,以下代码无法成功执行:

 Items[1].Name := 'Watch'; //will not compile

翻译自: https://www.thoughtco.com/declare-and-initialize-constant-arrays-1057596

delphi 常量数组

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值