gpt4 book ai didi

abap - 当结构包含字符串字段时,将结构转换为字符串失败

转载 作者:行者123 更新时间:2023-12-01 15:01:37 26 4
gpt4 key购买 nike

我有一个动态内部表<ft_dyn_tab> 。我想将内部表的每一行转换为类型 string通过字段符号<lf_string> :

LOOP AT <ft_dyn_tab> ASSIGNING <fs_dyn_wa>.
ASSIGN <fs_dyn_wa> to <lf_string> CASTING.
...
"other logic
...
ENDLOOP.

通常,CASTING当结构的所有字段都是字符类型时,工作正常。但是当一个字段的类型为 string 时,它给出一个运行时错误。谁能解释为什么?以及如何解决这个问题?

最佳答案

为什么仅包含类字符和字符串组件的结构无法“转换”为文本变量

原因由Strings的ABAP文档给出:

"A structure that contains a string is a deep structure and cannot be used as a character-like field in the same way as a flat structure.".

Deep :

"Deep: [...] the content [...] is addressed internally using references ([...], strings..."

Memory Requirement for Deep Data Objects :

"The memory requirement for the reference is 8 byte. [...] In strings, [...] an implicit reference is created internally."

ASSIGN - casting_spec :

"If the data type determined by CASTING is deep or if deep data objects are stored in the assigned memory area, the deep components must appear with exactly the same type and position in the assigned memory area. In particular, this means that individual reference variables can be assigned to only one field symbol that is typed as a reference variable by the same static type."

现在,编译器和运行时不允许您这样做的原因是,如果您转换整个深层结构,您可以更改 8 字节引用来访问内存中的任何位置,这可能很危险(How dangerous is it to access an array out of bounds?)并且很难分析后续的错误。在所有编程语言中,编译器都会尽可能防止越界访问或在运行时完成检查 ( Bounds checking )。

解决方法

您的问题发生在运行时,因为您使用动态创建的数据对象,但在编译时使用静态定义的数据对象会遇到完全相同的问题。下面是一个具有静态定义结构的简单解决方案。

您可以访问该结构的每个字段并将其连接到一个字符串:

DATA: BEGIN OF dyn_wa,
country TYPE c LENGTH 3,
city TYPE string,
END OF dyn_wa,
lf_string TYPE string.
FIELD-SYMBOLS: <lf_field> TYPE clike.

dyn_wa = VALUE #( country = 'FR' city = 'Paris' ).

DO.
ASSIGN COMPONENT sy-index OF STRUCTURE dyn_wa TO <lf_field>.
IF sy-subrc <> 0.
EXIT.
ENDIF.
CONCATENATE lf_string <lf_field> INTO lf_string RESPECTING BLANKS.
ENDDO.

ASSERT lf_string = 'FR Paris'. " one space because country is 3 characters

RESPECTING BLANKS 保留尾随空格,以模仿 ASSIGN ... CASTING

关于abap - 当结构包含字符串字段时,将结构转换为字符串失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55950556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com