---
title: "TStringList实例调用AddStrings 跟踪"
author: "explorer"
date: "2012-04-11T17:22:48Z"
tags: []
categories: ["编程语言"]
slug: "tstringlist-addstrings"
draft: false
lastmod: "2012-04-11T17:22:16Z"
id: 1483518
url: "https://explorer.iteye.com/blog/1483518"
---

创建了一个TStringList的实例并调用AddStrings，企图将ListBox1的所有Items加入sList实例（sList.AddStrings(ListBox1.Items)）。 开始以为VCL 处理有瑕疵，后发现环节都正确。

 

 

分析过程如下:

 

1.  观察Classes单元的TStrings.AddStrings(Strings: TStrings)的方法，其中有一句：AddObject(Strings\[I], Strings.Objects\[I]);

 

2.  走到了从源Strings的Get、GetObject方法

 

3.  因为ListBox的Items实例是这样创建的：  FItems := TListBoxStrings.Create; 所以 源Strings的GetObject方法走到了这里：TListBoxStrings.GetObject

 

4\. StdCtrls单元中，关于TListBoxStrings类两个重要方法如下：

 

function TListBoxStrings.GetObject(Index: Integer): TObject;  
...  
    Result := TObject(ListBox.GetItemData(Index));  
    if Longint(Result) = LB\_ERR then Error(SListIndexError, Index);

 

 

function TListBoxStrings.Add(const S: string): Integer;  
...  
  Result := SendMessage(ListBox.Handle, LB\_ADDSTRING, 0, Longint(PChar(S)));

 

 

5.  可以看出TListBoxStrings继承自TStrings，但是存储String、Object等均是根据 ListBox的句柄调用了Windows平台提供的LB\_ADDSTRING、LB\_GETITEMDATA 等消息

 

6.  因TListBoxStrings.GetObject 的思路是：如果返回值是 LB\_ERR (-1 )就抛出异常

 

7.  应用中ListBox是这样：ListBox1.Items.AddStrings(sList) 载入的，在VCL的曲折实现中依次经过 TStrings.AddObject  -&gt; TStrings.PutObject -&gt; TListBoxStrings.PutObject  -&gt; TCustomListBox.SetItemData -&gt; Windows 的SendMessage LB\_SETITEMDATA，并且nil 作为lParam 即Data传入给 ListBox的实例

 

8.  nil 空指针值为0， LB\_ERR值为 －1， 不是导致问题的原因，猜想错误。