加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – TCustomAttribute – “预期的常量表达式”编译错误

发布时间:2020-12-15 09:31:21 所属栏目:大数据 来源:网络整理
导读:给出以下代码段: 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
给出以下代码段:

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

解决方法

attributes documentation的相关部分是这样的:

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:

  • 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.

关键点在于constant expression是一个技术Pascal术语,与常量不同.我怀疑这是混乱的根源.

由于无法使用可传递给TGUID的常量表达式,因此您的属性运气不佳.实际上,拥有一个可以传递给open数组参数的常量表达式是不可能的.

我想你可以使用GUID的字符串表示来解决这个难题,但这会让你感到麻烦复制,并且无法传递GUID数组.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读