当我将另一个组件作为属性放入自定义组件时,为什么会出现“访问冲突”?

时间:2014-10-03 12:11:41

标签: delphi properties components

我希望我的组件在单个Colors属性中具有颜色属性。我已经用这种方式完成了,但我得到了#34;访问违规"。我不明白为什么,因为这是StackOverflow上发布的许多示例中的代码......

unit SuperList;

interface

uses Windows, Controls, Graphics, Classes, SysUtils, StdCtrls;

type

  TListColors = class(TPersistent)
  private
   FNormalBackg:TColor;
   FNormalText:TColor;
   FNormalMark:TColor;
  public
   constructor Create;
   procedure Assign(Source: TPersistent); override;
  published
   property NormalBackg:TColor read FNormalBackg write FNormalBackg default clRed;
   property NormalText:TColor  read FNormalText  write FNormalText  default clRed;
   property NormalMark:TColor  read FNormalMark  write FNormalMark  default clRed;
  end;

  TSuperList = class(TCustomControl)
  private
    FColors: TListColors;
    procedure SetListColors(const Value:TListColors);
  public
    procedure Paint; override;
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    property Colors:TListColors read FColors write SetListColors;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('Marus', [TSuperList]);
end;

//------ TListColors -----------------------------------------------------------

constructor TListColors.Create;
begin
 FNormalBackg:=clRed;
 FNormalText :=clRed;
 FNormalMark :=clRed;
end;

procedure TListColors.Assign(Source: TPersistent);
begin
 if Source is TListColors then begin
  FNormalBackg:=TListColors(Source).FNormalBackg;
  FNormalText:= TListColors(Source).FNormalText;
  FNormalMark:= TListColors(Source).FNormalMark;
 end
 else inherited;
end;

//------ TSuperList ------------------------------------------------------------

procedure TSuperList.SetListColors(const Value: TListColors);
begin
 FColors.Assign(Value);
end;

constructor TSuperList.Create(AOwner: TComponent);
begin
 inherited;
 Width:=200;
 Height:=100;
 Color:=clNone; Color:=clWindow;
 Colors:=TListColors.Create;
end;

destructor TSuperList.Destroy;
begin
 Colors.Free;
 inherited;
end;

procedure TSuperList.Paint;
begin
 Canvas.Brush.Color:=Color;
 Canvas.FillRect(Canvas.ClipRect);
end;

end.

1 个答案:

答案 0 :(得分:7)

在你的构造函数中,你有:

Colors:=TListColors.Create;

将其更改为:

FColors:=TListColors.Create;

您当前的代码正在调用属性设置器,该设置器正在尝试分配给未初始化的FColor。