Delphi: All constants are constant, but some are more constant than others?

前端 未结 7 1300
眼角桃花
眼角桃花 2021-01-03 20:54

Consider:

const 
   clHotlight: TColor = $00FF9933;
   clLink = clHotLight; //alias of clHotlight

[Error] file.pas: Constant expression expected


        
相关标签:
7条回答
  • 2021-01-03 21:50

    The problem arises because a typed constant is not, truly, a constant, as has been explained with varying degrees of clarity and success by others.

    What hasn't as yet been shown is how to work around the problem (in a large number of cases), though a couple came tantalisingly close to giving up that secret... :)

    In your specific case you can get around the problem by reversing the "aliasing" of the value and the typed constant declaration as follows:

    const
      clLink = $00FF9933;
      clHotlight: TColor = clLink;
    

    clLink now provides your true constant and clHotlight is the typed constant that has the same value as clLink.

    For the GUID's the same technique can be used, but you have to bear in mind the normal constant expression used to initialise a typed GUID constant - it doesn't use a record but a simple literal string, so:

    const
      ID_CONSTANT = '{AA1C8AF2-C290-40AB-9CF5-2888A46E1660}';
      GUID_CONSTANT: TGUID = ID_CONSTANT;
    

    NOTE: Such GUID constants are perfectly usable in all places where TGUID's are required, e.g. IsEqualGUID( tguid, GUID_CONSTANT ) etc.

    0 讨论(0)
提交回复
热议问题