Generics with Delphi 2009 Win32
With, as a bonus, anonymous routines and routine references
Date de publication : November 13th, 2008
I-B. What are generics?
This tutorial was not written for the beginner in Delphi, or for a programmer who has never practised object oriented programming. It requires a good knowledge of the Delphi language, and non-negligible knowledge of OOP.
As for generics, no prior knowledge is needed for a good understanding of this tutorial. But, seeing there are already many existing articles on generics in other languages, I will not cover in details questions of matters like "How to use generics well?". The next section will introduce briefly the reader to the subject, but if you do not already know what generics are, the best understanding will come with the rest of the tutorial, with examples.
Here are some (French-speaking) articles covering the subject of generics in other languages/platforms. The concepts are always the same, and a fair amount of undertaking is as well.
I-B. What are generics?
Generics are sometimes called generic parameters, a name which allows to introduce them somewhat better. Unlike a function parameter (argument), which has a value, a generic parameter is a type. And it parameterize a class, an interface, a record, or, less frequently, a method.
In order to ease the understanding immediately, here is an extract of the TList<T> class, which you may find in the Generics.Collections.pas unit.
You may readily see the weirdness of the type T. But is it really a type? No, it is a generic parameter. With this class at my disposal, if I need a list of Integers, I will use TList<Integer>, instead of a "simple" TList, along with many necessary casts in the code!
Generics thus allow, somehow, to declare a set of (potential) classes with a single code, or -more formally- a class template, but with one (or several) parameterized types, which you may change at will. Each time a new actual type is instanciated, you kind of write an entire new class, following its template, and, thus, make real one of those potential classes.
As I said before, I will not spread on the why and the how of generics. I will immediately go on with their daily use. If you think you still haven't got a clue on what I say, do not worry: everything is going to become clearer in a minute. You may also read the (French-speaking) tutorial Les génériques sous Delphi .NET written by Laurent Dardenne.
Copyright © 2008-2009 Sébastien Doeraene. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents, images, etc. sans l'autorisation expresse de l'auteur. Sinon vous encourez selon la loi jusqu'à trois ans de prison et jusqu'à 300 000 € de dommages et intérêts.
Copyright © 2000-2017 - www.developpez.com