【发布时间】:2016-03-17 18:11:30
【问题描述】:
如何设置组件对象属性值的默认值?
组件类代码:
unit CustomClass;
interface
uses
Classes;
type
TCustomClass = class;
TConfiguration = class;
TCustomClass = class (TComponent)
private
FConfiguration: TConfiguration;
procedure SetConfiguration(const Value: TConfiguration);
published
property Configuration: TConfiguration read FConfiguration write SetConfiguration;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
TConfiguration = class (TPersistent)
private
FDelay: Integer;
FSize: Integer;
procedure SetDelay(const Value: Integer);
procedure SetSize(const Value: Integer);
published
property Delay: Integer read FDelay write SetDelay;
property Size: Integer read FSize write SetSize;
public
procedure Assign(Source: TPersistent); override;
end;
implementation
{ TCustomClass }
constructor TCustomClass.Create(AOwner: TComponent);
begin
inherited;
Configuration.FileName:= 'FileName';
Configuration.Size := 10;
end;
destructor TCustomClass.Destroy;
begin
Configuration.Free;
inherited;
end;
procedure TCustomClass.SetConfiguration(const Value: TConfiguration);
begin
FConfiguration.Assign(Value);
end;
{ TConfiguration }
procedure TConfiguration.Assign(Source: TPersistent);
begin
inherited;
Delay := (Source as TConfiguration).Delay;
Size := (Source as TConfiguration).Size;
end;
procedure TConfiguration.SetDelay(const Value: Integer);
begin
FDelay := Value;
end;
procedure TConfiguration.SetSize(const Value: Integer);
begin
FSize := Value;
end;
end.
在我的 IDE 中,它将显示为对象属性已修改(粗体蓝色)。
我想在 TConfiguration 类属性上创建默认和存储函数,如下所示:
TConfiguration
interface
private
function FileNameStored: Boolean;
published
property FileName: string read FFileName write SetFileName stored FileNameStored;
property Size: Integer read FSize write SetSize default 10;
implementation
function TConfiguration.FileNameStored: Boolean;
begin
Result := FileName <> 'FileName';
end;
它将 TConfiguration 的属性着色为普通蓝色,但不是 TCustomClass 的 Configuration 属性,而且我想设置其默认值也不存在,它位于 TCustomClass 上,因为 TConfiguration 可能用于其他组件。
然后,我也想:
TCustomClass
interface
private
function ConfigurationStored: Boolean;
published
property Configuration: TConfiguration read FConfiguration write SetConfiguration stored ConfigurationStored;
implementation
function TCustomClass.ConfigurationStored: Boolean;
begin
Result := Configuration.FileName <> 'FileName' and
Configuration.Size <> 10;
end;
但是,这只会将 TCustomClass 配置属性颜色设置为普通蓝色,而不是其属性。
回答
正如@RemyLebeau 所指出的(在第一个和最佳答案中),代码中存在错误。 在那个组件和那种情况下,我决定不对属性设置任何默认值。
【问题讨论】:
-
您是否打算将配置对象拖放到表单上并将自定义类拖放到表单上,然后将它们连接起来?或者您是否希望配置对象成为属于自定义类的属性,而不必手动创建和分配?
-
那么你真的忽略了一些明显的事情,正如 Remy 指出的那样。他表明您需要显式创建(在您的类构造函数中)和释放(在您的类析构函数中)属于您的对象(是不可分割的部分)的所有 TObject 类型。你有正确的基类,所以这很好。您可能希望将 OnChange:TNotificationEvent 添加到您的配置对象。所以它可以调用主类并让它在有人写入配置属性时做一些事情。
-
@WarrenP 是的。我修复了它,但正如@NGLN 指出的那样,在问题上纠正它是没有意义的,因为它使答案变得不必要。
OnChange: TNotificationEvent确实是一个很好的建议,我喜欢它,因为如果它们是类私有变量,我可以更改属性的stored值。谢谢。
标签: class delphi properties components delphi-2009