布尔值的类默认属性设置为 true 在运行时给出 false
我有一个带有布尔属性的简单组件类:
TmyClass = class(TComponent)
private
fSomeProperty: boolean;
published
property SomeProperty: boolean
read fSomeProperty
write fSomeProperty
default true;
end;
我将其放在表单上,将其设置为 true(SomeProperty 设置为 false,为什么?),但是当我试图从运行时访问 SomeProperty 它给了我错误。为什么会这样呢?
I've got a simple component class with boolean property:
TmyClass = class(TComponent)
private
fSomeProperty: boolean;
published
property SomeProperty: boolean
read fSomeProperty
write fSomeProperty
default true;
end;
I put it on my form, set it to true (SomeProperty is set to false, why?), but when i'm trying to access SomeProperty from run-time it's giving me false. Why is that so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那是因为
default
说明符实际上并不将值分配给属性,它只是告诉流系统哪个值是默认值(因此不需要保存)。您仍然需要将构造函数中的 prop/field 初始化为所需的默认值。这在帮助中有记录,顺便说一句,请阅读“存储说明符”部分Thats because the
default
specifier don't actually assign the value to the property, it just says to the streaming system which value is the default (and thus doesn't need to be saved). You still have to initialize the prop/field in the constructor to the desired default value. This is documented in the help btw, read the "Storage Specifiers" section您还应该在构造函数中将该属性设置为 True - 否则会出现错误:
默认值决定 *.DFM 文件中将存储的内容。如果您在设计时将
FSomeProperty
设置为True
,并且FSomeProperty
的默认值为True
,则FSomeProperty
将不会存储在 *.DFM 中。如果您没有在构造函数中将
FSomeProperty
初始化为True
,则会出现您所描述的错误 -FSomeProperty
出现False
在运行时,尽管它在设计时设置为True
。You should also set the property to True in the constructor - otherwise it is an error:
Default values determine what will be stored in *.DFM file. If you set
FSomeProperty
toTrue
at design time, and default value forFSomeProperty
isTrue
, thenFSomeProperty
will not be stored in *.DFM.If you don't initialize
FSomeProperty
toTrue
in the constructor you get an error you described -FSomeProperty
appearsFalse
at runtime, though it was setTrue
at design time.