SaveTo StringHelper?

匆匆过客 提交于 2019-12-13 05:26:33

问题


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:


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.



来源:https://stackoverflow.com/questions/34139196/saveto-stringhelper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!