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

Mar*_*unu 0 delphi components properties

我希望我的组件在一个单一的属性中具有颜色属性Colors.而且我已经这样做了,但我得到了"访问冲突".我不明白为什么,因为这是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.
Run Code Online (Sandbox Code Playgroud)

Kei*_*ler 7

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

Colors:=TListColors.Create;
Run Code Online (Sandbox Code Playgroud)

将其更改为:

FColors:=TListColors.Create;
Run Code Online (Sandbox Code Playgroud)

您当前的代码正在调用属性setter,它正在尝试分配给未初始化的FColor.

  • 同样,在析构函数中,你应该使用`FColors.Free;`而不是`Colors.Free;` (2认同)