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

詳測 Generics Collections TList (11): Create

編輯:Delphi

unit Unit1; 
 
interface 
 
uses 
 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 
 Dialogs, StdCtrls; 
 
type 
 TForm1 = class(TForm) 
  Button1: TButton; 
  Button2: TButton; 
  Button3: TButton; 
  procedure Button1Click(Sender: TObject); 
  procedure Button2Click(Sender: TObject); 
  procedure Button3Click(Sender: TObject); 
 end; 
 
var 
 Form1: TForm1; 
 
implementation 
 
{$R *.dfm} 
 
uses Generics.Collections, Generics.Defaults; 
 
var 
 i: Integer; 
 str: string; 
 
//無參數的建立 
procedure TForm1.Button1Click(Sender: TObject); 
var 
 List: TList<Integer>; 
begin 
 List := TList<Integer>.Create(); 
 
 List.AddRange([11,22,33]); 
 str := ''; 
 for i in List do str := str + IntToStr(i) + ' '; 
 ShowMessage(str); {11 22 33 } 
 
 List.Free; 
end; 
 
//可以基於另一個列表建立 
procedure TForm1.Button2Click(Sender: TObject); 
var 
 List,ListTmp: TList<Integer>; 
begin 
 ListTmp := TList<Integer>.Create(); 
 ListTmp.AddRange([1, 2, 3]); 
 
 List := TList<Integer>.Create(ListTmp); 
 
 str := ''; 
 for i in List do str := str + IntToStr(i) + ' '; 
 ShowMessage(str); {1 2 3 } 
 
 ListTmp.Free; 
 List.Free; 
end; 
 
//可在建立時同時指定排序器 
procedure TForm1.Button3Click(Sender: TObject); 
var 
 List: TList<Integer>; 
 Comparer: IComparer<Integer>; 
begin 
 {建立排序器} 
 Comparer := TComparer<Integer>.Construct( 
  function(const n1,n2: Integer): Integer 
  begin 
   Result := n2 - n1; 
  end 
 ); 
 
 List := TList<Integer>.Create(Comparer); 
 List.AddRange([2, 3, 1]); 
 
 List.Sort; {會根據建立時指定的排序器排序} 
 
 str := ''; 
 for i in List do str := str + IntToStr(i) + ' '; 
 ShowMessage(str); {3 2 1 } 
 
 List.Free; 
end; 
 
end. 


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