Generics dan For Loop


Generics adalah salah satu fitur baru dari RAD Studio 2009. Generic merupakan fitur penggunaan tipe data dengan parameter. Masih ingat penggunaan TList? Setiap kali kita menambahkan object di dalam TList kita harus melakukan casting setiap kali akan membacanya. Dengan generic, kita tidak perlu lagi melakukannya!

TPeople = class(TObject)
private
FName: String;
procedure SetName(const Value: String);
public
property Name: String read FName write SetName;
end;

Jadul Version (masih disupport juga lho) :

for i := 0 to peopleList.Count – 1 do
begin
ShowMessage((peopleList[i] as TPeople).Name);
end;

while peopleList.Count > 0 do
begin
peopleList[0].Free;
peopleList.Delete(0);
end;

Versi menggunakan generic (awas perlu uses Generics.Collections; )

var
peopleList: TList<TPeople>;
people: TPeople;
begin
peopleList := TList<TPeople>.Create; //deklarasi List of TPeople

people := TPeople.Create;
people.Name := ‘Wisnu’;
peopleList.Add(people);

people := TPeople.Create;
people.Name := ‘Widiarta’;
peopleList.Add(people);

for people in peopleList do //for loopnya dah keren!
begin
ShowMessage(people.Name);
people.free;
end;
peopleList.Free;
end;

Iklan

Posted on Oktober 1, 2009, in Pemrograman, Ulasan and tagged . Bookmark the permalink. Tinggalkan komentar.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: