TCustomAttribute-“期望的常量表达式”编译错误
给出以下代码片段:
type
MyIntf = interface
['{C6184693-663E-419F-B2DA-4DA1A0E33417}']
procedure Foo;
end;
InvisiblePropInterfaces = class(TCustomAttribute)
private
FGUIDS: array of TGUID;
public
constructor Create(const GUIDS: array of TGUID);
end;
[InvisiblePropInterfaces([MyIntf])] // <-- Constant expression expected error
TMyClass = class(TInterfacedObject, MyIntf)
procedure Foo;
end;
为什么编译器认为这不是常量表达式? 但鉴于我像这样使用 InvisiblePropInterfaces,编译器就很高兴?
...
var
I: InvisiblePropInterfaces;
begin
I:= InvisiblePropInterfaces.Create([MyIntf]);
...
Given the following code snippet:
type
MyIntf = interface
['{C6184693-663E-419F-B2DA-4DA1A0E33417}']
procedure Foo;
end;
InvisiblePropInterfaces = class(TCustomAttribute)
private
FGUIDS: array of TGUID;
public
constructor Create(const GUIDS: array of TGUID);
end;
[InvisiblePropInterfaces([MyIntf])] // <-- Constant expression expected error
TMyClass = class(TInterfacedObject, MyIntf)
procedure Foo;
end;
Why does the compiler think this is not a constant expression ?
But given that I use InvisiblePropInterfaces like this, the compiler is just happy?
...
var
I: InvisiblePropInterfaces;
begin
I:= InvisiblePropInterfaces.Create([MyIntf]);
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
属性文档的相关部分如下:
关键点是 常量表达式 是一个 Pascal 技术术语,而不是与常数相同。我怀疑这就是混乱的根源。
由于不可能有可传递给
TGUID
的常量表达式,因此您的属性不走运。事实上,不可能有一个可以传递给开放数组参数的常量表达式。我想您可以使用 GUID 的字符串表示形式来解决这个难题,但这会给您带来混乱的重复,并且无法传递 GUID 数组。
The pertinent section of the attributes documentation is this:
The key point is that a constant expression is a technical Pascal term that is not the same thing as a constant. I suspect that this is the root of the confusion.
Since it is not possible to have a constant expression that can be passed to a
TGUID
, you are out of luck with your attribute. Indeed it is just as impossible to have a constant expression that can be passed to an open array parameter.I suppose that you could use the string representation of the
GUID
to solve the conundrum but that will leave you with messy duplication and an inability to pass arrays of GUIDs.这是一个已知的限制。 TGUID 被声明为记录类型,并且无法创建记录常量表达式。
This is a known limitation. TGUID is declared as a record type and there is no way to make a record constant expression.