覆盖TStringList.Delimiter

时间:2016-01-28 07:39:07

标签: delphi delphi-2007

TStringList.Delimiter是一个TChar。这使得Delimitertext成为

成为可能
Test,Test,Test,Test

但我希望将'和'作为结果的分隔符

Test and Test and Test and Test

当然我可以像这样解决它

s := List[0];
for i := 1 to List.Count - 1 do
  s := s + ' and ' + List[i];

但是做起来会更优雅

List.Delimiter := ' and ';
s := List.DelimiterText;

所以我尝试使用此代码覆盖TStringList;

unit Unit5;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Menus, StdCtrls, cxButtons, cxTextEdit,
  cxMemo;

type
  TForm5 = class(TForm)
    cxMemo1: TcxMemo;
    cxButton1: TcxButton;
    procedure cxButton1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  TAttracsStringList = class(TStringList)
  private
    FDelimiter: String;
    procedure SetDelimiter(const Value: String);
    function GetDelimiter: String;
  public
    property Delimiter: String read GetDelimiter write SetDelimiter;
  end;

var
  Form5: TForm5;

implementation

{$R *.dfm}

function TAttracsStringList.GetDelimiter: String;
begin
  Result := FDelimiter;
end;

procedure TAttracsStringList.SetDelimiter(const Value: String);
begin
  FDelimiter := Value;
end;

procedure TForm5.cxButton1Click(Sender: TObject);
var
  vList: TAttracsStringList;
  i: Integer;
begin
  vList := TAttracsStringList.Create;
  try
    vList.Delimiter := ' and ';
    for i := 0 to 3 do
      vList.Add('Test');

    cxMemo1.Text := vList.DelimitedText;
  finally
    vList.Free;
  end;
end;

end.

它不起作用。备忘录得到了结果

Test,Test,Test,Test

我该如何解决这个问题?

修改 我现在看到GetDelimiter和SetDelimiter在TStringList中是私有的。所以我无法覆盖它们。想知道是否有办法实现我的目标?

EDIT2 我通过添加

解决了这个问题
property DelimitedText: String read GetDelimitedText;

方法

function TAttracsStringList.GetDelimitedText: String;
var
  i: Integer;
begin
  if Count > 0 then
  begin
    Result := Strings[0];

    for i := 1 to Count - 1 do
      Result := Result + Delimiter + Strings[i];
  end
  else
    Result := '';
end;

因此,如果某人没有更聪明的方式,我认为这已经解决了。

1 个答案:

答案 0 :(得分:4)

确实有另一种解决方案:

library(ggplot2)

a = c(4, 2)
x = c(1:4)
y = c(1:4)

# This works (τ^-1 = 4 s^-1):

l <- paste("tau^-1 ==", a[1], "*~s^-1")
qplot(x, y) + annotate("text", x = 1.5, y = 3.5, parse=TRUE, label = l);

# But I would like to see something like this ( τ^-1 = 4 ± 2 s^-1): 

l <- paste("tau^-1 ==", a[1], "\u00B1", a[2], "*~s^-1")
qplot(x, y) + annotate("text", x = 1.5, y = 3.5, parse=TRUE, label = l);

作为缺点,不引用个别条目。