如何在 ABAP 对象中将填充的 structure/table 定义为 class 常量

How can I define a filled structure/table as class constant in ABAP Objects

我想要一个 immutable 预定义 table 作为 class 变量。如何定义这样的变量?

我会创建一个属性并将其标记为 "Read Only",您可以通过构造函数或 Set-Method 设置它。

您不能在 ABAP 中使用 class 常量来这样做。 documentation 明确表示:

  • You can specify a start value val for the ABAP types string and xstring only.

  • Constant internal tables, reference variables, and structures with not purely character-like flat components can be assigned their initial value by IS INITIAL only, and are therefore always initial.

正如 Tapio 所建议的,你唯一的选择是只读属性,我也建议你使用静态属性,它可以在构造函数中初始化。

例如

CLASS lcl_test DEFINITION.
  PUBLIC SECTION.
  CLASS-DATA: itab TYPE RANGE OF i READ-ONLY.
  METHODS:
      constructor.
ENDCLASS.
CLASS lcl_test IMPLEMENTATION.
  METHOD constructor.
      itab = VALUE #( sign = 'I'  option = 'BT' ( low = 1  high = 10 )
                                                ( low = 21 high = 30 )
                                                ( low = 41 high = 50 )
                                  option = 'GE' ( low = 61 )  ).
  ENDMETHOD.
ENDCLASS.

毕竟那段时间可以解决的一件事是:

  • 创建您的列表
  • 将其序列化并保存为只读字符串
  • 创建一个反序列化的 getter

这是一个老问题,答案很简单: 只需创建一个 returns 常量数据的静态方法 (getter)。

而不是使用:

data(ls_sample) = lcl_myclass=>cs_data.

使用:

data(ls_sample) = lcl_myclass=>cs_data( ).