Generic Types in Delphi
Generics, a powerful addition to Delphi, were introduced in Delphi 2009 as a new language feature. Generics or generic types (also know as parametrized types), allow you to define classes that don't specifically define the type of certain data members.
As an example, instead of using the TObjectList type to have a list of any object types, from Delphi 2009, the Generics.Collections unit defines a more strongly typed TObjectList.
Simple Generics Type Example in Delphi
Here's how to define a simple generic class:
type
TGenericContainer<T> = class
Value : T;
end;
With the following definition, here's how to use an integer and string generic container:
var
genericInt : TGenericContainer<integer>;
genericStr : TGenericContainer<string>;
begin
genericInt := TGenericContainer<integer>.Create;
genericInt.Value := 2009; //only integers
genericInt.Free;
genericStr := TGenericContainer<string>.Create;
genericStr.Value := 'Delphi Generics'; //only strings
genericStr.Free;
end;
No comments:
Post a Comment