问题描述
给出以下代码段:
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,编译器很高兴吗?
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]);
...
推荐答案
是:
- 仅允许使用常量表达式,包括集合,字符串和序数表达式。
- out和var参数不能使用,因为它们需要对传递的参数的地址进行运行时评估。
- Addr ()不能使用内在和@运算符。
- 可以使用TypeInfo()运算符来传递类型信息,因为RTTI块地址在编译时是已知的。
- 允许使用类引用,因为在编译时就知道了元类地址(例如TypeInfo()的情况)。
- Only constant expressions are allowed, including sets, strings, and ordinal expressions.
- out and var parameters cannot be used, because they require run-time evaluation of addresses of passed parameters.
- Addr() intrinsic and @ operator cannot be used.
- The TypeInfo() operator can be used to pass type information, because the RTTI block addresses are known at compile time.
- Class references are allowed, because the metaclass addresses (as the case of TypeInfo()) are known at compile time.
关键点是是Pascal技术术语,与常数不同。我怀疑这是造成混乱的根源。
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.
由于不可能有可以传递给 TGUID
,您的属性不符合要求。确实,有一个常量表达式可以传递给开放数组参数也是不可能的。
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.
我想您可以使用<$ c的字符串表示形式$ c> GUID 来解决这个难题,但这会使您陷入混乱,并且无法传递GUID数组。
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.
这篇关于TCustomAttribute-“期望常量表达式”;编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!