TCustomAttribute-“期望常量表达式”;编译错误 [英] TCustomAttribute - "Constant expression expected" compile error

查看:71
本文介绍了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,编译器很高兴吗?

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]);
...


推荐答案

属性文档是:


重要的是要理解传递给属性构造函数的值必须是常量表达式。由于这些值必须直接嵌入到生成的二进制文件中,因此无法传递需要运行时评估的表达式。这对在编译时可以传递给属性的信息提出了一些限制:

It is important to understand that the values passed to the attribute's constructor must be constant expressions. Because those values must be embedded directly into the resulting binary, it is impossible to pass an expression that requires run-time evaluation. This raises a few limitations to the information that can be passed to the attribute at compile time:


  • 仅允许使用常量表达式,包括集合,字符串和序数表达式。

  • 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-“期望常量表达式”;编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆