程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> Delphi中的容器類(7)

Delphi中的容器類(7)

編輯:Delphi

同對象關聯

前面說了我們可以將字符串同對象綁定起來,我們可以使用AddObject或者InsertObject方法向列表添加同字符串關聯的對象,也可以通過Objects屬性直接將對象同特定位置的字符串關聯。此外TStrings類還提供了IndexOfObject方法返回指定對象的索引,同樣的Delete,Clear和Move等方法也可以作用於對象。不過要注意的是我們不能向字符串中添加一個沒有同字符串關聯的對象。

同視圖交互

剛剛學習使用Delphi的人都會為Delphi IDE的強大的界面交互設計功能所震驚,比如我們在窗體上放上一個ListBox,然後在object Inspector中雙擊它的Items屬性(TStrings類型),在彈出的對話框中,見下圖,我們輸入一些字符串後,點擊確定,關閉對話框,就會看到窗體上的ListBox中出現了我們剛才輸入的字符串。

可以我們在TStrings和默認的實現類TStringList的源代碼中卻找不到同ListBox相關的代碼,那麼這種界面交互是如何做到的呢?

秘密就在於TListBox的Items屬性類型實際上是TStrings的基類TListBoxStrings類,我們看一下這個類的定義:

TListBoxStrings = class(TStrings)
 private
  ListBox: TCustomListBox;
 protected

 public
  function Add(const S: string): Integer; override;
  procedure Clear; override;
  procedure Delete(Index: Integer); override;
  procedure Exchange(Index1, Index2: Integer); override;
  function IndexOf(const S: string): Integer; override;
  procedure Insert(Index: Integer; const S: string); override;
  procedure Move(CurIndex, NewIndex: Integer); override;
 end;

可以看到TListBoxStrings類實現了TStrings類的所有抽象方法,同時在內部有一個ListBox的私有變量。我們再看一下TListBoxStrings的Add方法:

function TListBoxStrings.Add(const S: string): Integer;
begin
 Result := -1;
 if ListBox.Style in [lbVirtual, lbVirtualOwnerDraw] then exit;
 Result := SendMessage(ListBox.Handle, LB_ADDSTRING, 0, Longint(PChar(S)));
 if Result < 0 then raise EOutOfResources.Create(SInsertLineError);
end;

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved