【问题标题】:Override Read and Write of Property of base class重写基类属性的读写
【发布时间】:2015-05-06 11:28:40
【问题描述】:

我想创建一个新的组件,它的行为与 TEdit 完全一样,但将一些字符替换为其中输入的文本。 例如,当有人在新组件中键入“abc”时,我希望文本属性在源代码中读取时返回“aac”。

type
  TMyEdit = class(TEdit)
  public
    property Text : TCaption read GetText;
  end;

类似的东西。

是否可以用新的读取功能覆盖现有属性,而不更改该属性的写入功能?

问候

【问题讨论】:

  • 是Delphi XE的VCL

标签: delphi


【解决方案1】:

如前所述:

最好的方法是使用 TMaskEdit

但如果你真的想实现该行为,那么可以这样做:

type
  TMyEdit = class(TEdit)
  private
    function GetText: TCaption;
    procedure SetText(const Value: TCaption);
  public
    property Text: TCaption read GetText write SetText;
  end;

{ TMyEdit }

function TMyEdit.GetText: TCaption;
begin
  Result := 'TMyEdit' + inherited Text;
end;

procedure TMyEdit.SetText(const Value: TCaption);
begin
  inherited Text := Value;
end;

简而言之,我创建 GetTextSetText settext 只是调用继承的 Text 属性,而 GetText 更改结果

【讨论】:

  • 您好,感谢您的建议。但是,如果我尝试从此组件中读取文本,我会遇到很多访问冲突。你碰巧知道问题出在哪里吗?
  • 是的。我犯了一个错误。现在应该修好了
  • 谢谢你,正是我想要的!
【解决方案2】:
TMyEdit = class(TEdit)
protected
   procedure Change; override;
 end;

procedure TMyEdit.Change;
begin
  Self.Text := StringReplace(Self.Text, 'aaa', 'ccc');
  inherited;
end;

【讨论】:

  • 但是最好的方法是使用 TMaskEdit
  • 我认为这不是问题所要求的。我明白了,因为 OP 希望获得与 Text 属性设置的文本不同的文本。您正在修改该属性。
猜你喜欢
  • 2012-03-23
  • 2014-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-20
  • 1970-01-01
相关资源
最近更新 更多