据我查资料":="只是地址的引用而"assign"则是对象的复制
我在窗体放置了分别Listbox1,Listbox2;
Listbox1.items中已经有数据了
在一个Button1Click中写代码如下
begin
Listbox2.items:=Listbox1.items;
listbox1.items.clear;
showmessage(Listbox2.items[0]);//这句仍能正常运行;
end;
我想既然":="是地址的引用,"showmessage(Listbox2.items[0])"应该报错才对,为什么仍能运行?
请大家帮解释一下,谢谢!
ListBox1.Items.Add('adsfasdfa'); //ListBox2.Items中并没有添加新项
property Items: TStrings read FItems write SetItems;
...
procedure TCustomListBox.SetItems(Value: TStrings);
begin
if Style in [lbVirtual, lbVirtualOwnerDraw] then
case Style of
lbVirtual: Style := lbStandard;
lbVirtualOwnerDraw: Style := lbOwnerDrawFixed;
end;
Items.Assign(Value);
end;
"ListBox2.Items := ListBox1.Items"与"ListBox2.Items.assign(ListBox1.Items)"
是一回事,没有什么区别,而且也不会导致内存的泄漏.是不是这样?
---------------------------这句话在深入理解Delphi对象机制和类库结构后,你会发现这是很笼统的说法。因为Assign只是TPersistent的一个虚方法,具体的实现可以是千差万别的,要看每个具体类来定。例如说,如果Assign我实现为“FItems := Value”。那这个Assign就是地址引用,而不是对象内容赋值了。遇到这种情况,最好是自己去看看该类的源代码是怎么实现这个方法的。DELPHI公开了VCL的代码,这就再方便不过了。