【发布时间】:2018-06-27 09:43:58
【问题描述】:
在阅读了 Embarcadero 关于 procedural types 和 anonymous methods 和 David Heffernan's explanation 的文档后,我仍然不太明白为什么编译器禁止初始化函数引用的常量数组,如下例中的 C_BAR。
program MyProgram;
{$APPTYPE CONSOLE}
{$R *.res}
type
TFoo = function: Integer;
TBar = reference to function: Integer;
function FooBar: Integer;
begin
Result := 42;
end;
const
// This works
C_FOO: array[0..0] of TFoo = (FooBar);
// These lines do not compile
// C_BAR: array[0..0] of TBar = (FooBar); // TBar incompatible with Integer
// C_BAR: array[0..0] of TBar = (@FooBar); // TBar incompatible with Pointer
var
Foo: array[0..0] of TFoo;
Bar: array[0..0] of TBar;
begin
Foo[0] := FooBar; // Foo[0] = MyProgram.FooBar
Bar[0] := FooBar; // Bar[0] = MyProgram$1$ActRec($1CC8CF0) as TBar
Foo[0] := C_FOO[0]; // Foo[0] = MyProgram.FooBar
Bar[0] := C_FOO[0]; // Bar[0] = MyProgram$1$ActRec($1CC8CF0) as TBar
end.
使用调试器,我可以看到 Bar[0] 等于某个地址(我认为?),这告诉我在我的理解背后发生了一些事情......
那么在我的示例中是否可以初始化像 C_BAR 这样的常量数组?如果是,怎么做,否则,为什么?
【问题讨论】: