SaveTo StringHelper?

2019-09-02 06:43发布

I need a StringHelper which saves a string to a file:

var
  s: string;
begin
  s := 'Some text';
  s.SaveTo('C:\MyText.txt');
end;

Unfortunately, this is not possible. Is it possible to add such a StringHelper?

1条回答
We Are One
2楼-- · 2019-09-02 07:10

It is possible to add such a helper. For instance:

type
  TMyStringHelper = record helper for string
    procedure SaveTo(const FileName: string);
  end;

The downside to doing so is that this will replace the string helper that is provided by the RTL. If you don't use it, that won't matter. If you do use it, then that's a problem that cannot readily be overcome.

You could look at this a different way. Instead of trying to use a helper on the string type, you could use TFile.WriteAllText instead.

TFile.WriteAllText(FileName, 'Some text', TEncoding.UTF8);

Obviously you can use a different encoding if you prefer.

查看更多
登录 后发表回答