Why does memo.Lines use TStrings instead of TStringList?

ぐ巨炮叔叔 提交于 2019-12-08 14:34:13

问题


Why does Memo.Lines use the abstract class TStrings? Why doesn't it use TStringList instead?

And should I convert it to TStringList before working with it?


回答1:


TMemo.Lines, TListBox.Items, TComboBox.Items, etc. ; all are declared as TStrings. Beware, talking about the property that is! The internal created types are TMemoStrings, TListBoxStrings and TComboBoxStrings respectively, which are all descendants of TStrings and differ all in way of storage.

And why? For interchangeability and interoperability. So every TStrings-descendant has the same properties, and so you can do:

Memo1.Lines := ListBox1.Items;

How to use? Well, a TStrings property like TMemo.Lines works just fine. You can add, delete, change, renew and clear the strings (and objects) on the property, because internally it is a TMemoStrings which implements all this interaction. Declaration <> implementation.

But when you want any special handling, e.g. like sorting which TStringList provides, then you need help. You cannot typecast nor convert a TMemo.Lines to a TStringList, because it isn't one, but instead you need to create an intermediate object for this special processing:

var
  Temp: TStringList;
begin
  Temp := TStringList.Create;
  try
    Temp.Assign(Memo1.Lines);
    Temp.Sort;
    Memo1.Lines.Assign(Temp);
  finally
    Temp.Free;
  end;
end;


来源:https://stackoverflow.com/questions/11122197/why-does-memo-lines-use-tstrings-instead-of-tstringlist

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