如何使用子属性编写属性?

Maw*_*awg 7 delphi

例如,像Font一样.谁能举一个非常简单的例子?也许只是一个有两个子属性的属性


编辑:我的意思是,当我在对象检查器中查看字体时,它有一个小加号,我可以单击以设置字体名称"times new roman",字体大小"10"等等.如果我使用错误的术语,Sorrry,这就是我所说的"子属性".

RRU*_*RUZ 15

您所要做的就是创建一个新的已发布属性,该属性指向已发布属性的类型.

检查此代码

  type
    TCustomType = class(TPersistent) //this type has 3 published properties
    private
      FColor : TColor;
      FHeight: Integer;
      FWidth : Integer;
    public
      procedure Assign(Source: TPersistent); override;
    published
      property Color: TColor read FColor write FColor;
      property Height: Integer read FHeight write FHeight;
      property Width : Integer read FWidth write FWidth;
    end;

    TMyControl = class(TWinControl) 
    private
      FMyProp : TCustomType;
      FColor1 : TColor;
      FColor2 : TColor;
      procedure SetMyProp(AValue: TCustomType);
    public
      constructor Create(AOwner: TComponent); override;
      destructor Destroy; override;
    published
      property MyProp : TCustomType read FMyProp write SetMyProp; //now this property has 3 "sub-properties" (this term does not exist in delphi)
      property Color1 : TColor read FColor1 write FColor1;
      property Color2 : TColor read FColor2 write FColor2;
    end;

  procedure TCustomType.Assign(Source: TPersistent);
  var
    Src: TCustomType;
  begin
    if Source is TCustomType then
    begin
      Src := TCustomType(Source);
      FColor := Src.Color;
      Height := Src.Height;
      FWidth := Src.Width;
    end else
      inherited;
  end;

  constructor TMyControl.Create(AOwner: TComponent);
  begin
    inherited;
    FMyProp := TCustomType.Create;
  end;

  destructor TMyControl.Destroy;
  begin
    FMyProp.Free;
    inherited;
  end;

  procedure TMyControl.SetMyProp(AValue: TCustomType);
  begin
    FMyProp.Assign(AValue);
  end;
Run Code Online (Sandbox Code Playgroud)

  • TMyControl.MyProp属性的setter不应直接写入FMyProp.这将泄漏原始的FMyProp对象并取得调用者对象的所有权.相反,它需要使用调用FMyProp.Assign()的setter方法,然后TCustomType需要实现Assign(). (6认同)