【问题标题】:How do I code a property with sub-properties?如何使用子属性对属性进行编码?
【发布时间】:2010-09-16 08:40:31
【问题描述】:

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


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

【问题讨论】:

    标签: delphi


    【解决方案1】:

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

    检查此代码

      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;
    

    【讨论】:

    • TMyControl.MyProp 属性的设置器不应直接写入 FMyProp。这将泄漏原始 FMyProp 对象并获得调用者对象的所有权。相反,它需要使用调用 FMyProp.Assign() 的 setter 方法,然后 TCustomType 需要实现 Assign()。
    【解决方案2】:

    你是什么意思,子属性? Delphi 中没有这样的东西。

    也许您的意思是对象组合,其中一个对象包含对另一个对象的引用,例如 -

    interface
    
    type
    TObj1 = class
    private
      FFont: TFont;  
      property Font: TFont read FFont;
    end;
    
    ...
    
    implementation
    
    var
      MyObj: TObj1;
    begin
      MyObj1 := TObj1.Create;
      MyObj1.Font.Name := 'Arial';
    

    【讨论】:

    • (+1 感谢您的回复)我的意思是,当我在对象检查器中查看字体时,它有一个小加号,我可以单击它来设置字体名称“times new roman”,字体大小“ 10”等。抱歉,如果我使用了错误的术语,这就是我所说的“子属性”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    相关资源
    最近更新 更多