将ListBox中的字符串转换为List <String>

And*_*rew 2 delphi tlist tlistbox

TListBox组件包含一组行(字符串).如何将此设置作为列表TList?下面的代码示例不会给出所需的结果.(Сode不编译)

MyList  := TList<String>.Create(MyListBox);
MyList  := TList<String>.Create(MyListBox.Items);
MyList  := TList<String>.Create(MyListBox.Items.ToStringArray);
Run Code Online (Sandbox Code Playgroud)

是否可以在不使用循环的情况下执行此操作?谢谢!

Dav*_*nan 5

你可以这样做:

MyList := TList<string>.Create;
try
  MyList.AddRange(MyListBox.Items.ToStringArray);
  ....
finally
  MyList.Free;
end;
Run Code Online (Sandbox Code Playgroud)

如果要在构造函数中分配项,则需要一个实例TEnumerable<string>.TStrings从外面嫁接起来并不容易.所以我认为上面的代码可能是最干净的.