【问题标题】:Class default property of boolean set to true gives false on run-time布尔值的类默认属性设置为 true 在运行时给出 false
【发布时间】:2011-08-04 15:22:14
【问题描述】:

我有一个带有布尔属性的简单组件类:

  TmyClass = class(TComponent)
    private
      fSomeProperty: boolean;
    published
      property SomeProperty: boolean 
                  read fSomeProperty 
                  write fSomeProperty
                  default true;

  end;

我把它放在我的表单上,将它设置为 true(SomeProperty 设置为 false,为什么?),但是当我尝试访问时 SomeProperty 从运行时它给了我错误。为什么会这样?

【问题讨论】:

    标签: delphi delphi-2010


    【解决方案1】:

    那是因为default 说明符实际上并没有将值分配给属性,它只是告诉流系统哪个值是默认值(因此不需要保存)。您仍然必须将构造函数中的 prop/field 初始化为所需的默认值。这记录在help btw 中,请阅读“Storage Specifiers”部分

    【讨论】:

    • +1;我在default 说明符上没有发现任何有用的东西,除了在对象检查器中,当您从default 更改某些属性的值时,它以粗体突出显示;如果你把它改回default,粗体样式就会被移除。
    • 正如@ain 所说,请阅读帮助或 DocWiki 的存储说明符部分。这说:Note: Property values are not automatically initialized to the default value. That is, the default directive controls only when property values are saved to the form file, but not the initial value of the property on a newly created instance.
    • 所以要修复它,添加构造函数代码FSomeProperty := true
    【解决方案2】:

    您还应该在构造函数中将属性设置为 True - 否则会出错:

    constructor TMyClass.Create(AOwner: TComponent);
    begin
      inherited;
      FSomeProperty:= True;
      ...
    end;
    

    默认值确定将存储在 *.DFM 文件中的内容。如果您在设计时将FSomeProperty 设置为True,并且FSomeProperty 的默认值为True,则FSomeProperty 将不会存储在*.DFM 中。

    如果您没有在构造函数中将 FSomeProperty 初始化为 True,则会收到您描述的错误 - FSomeProperty 在运行时出现 False,尽管它在设计时设置为 True

    【讨论】:

      猜你喜欢
      • 2015-09-19
      • 1970-01-01
      • 2020-06-23
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-23
      相关资源
      最近更新 更多