Class Constraints

The simplest constraint you can adopt is a class constraint. To use it, you can declare generic type as: type

TSampleClass <T: c1ass> = class

By specifying a class constraint you indicate that you can use only object types as generic types. With the following declaration (taken from the ClassContraint project): type

TSampleClass <T: c1ass> = class private data: T; publ ic procedure One; function ReadT: T; procedure SetT (t: T);


you can create the first two instances but not the third:

samp1e1: TSamp1eClass<TButton>; samp1e2: TSamp1eClass<TStrings>; samp1e3: TSamp1eClass<Integer>; // Error

The compiler error caused by this last declaration would be: | E2511 Type parameter 'T' must be a class type

What's the advantage of indicating this constraint? In the generic class methods you can now call any TObject method, including virtual ones! This is the One method of the TSampleClass generic class75:

procedure TSamp1eClass<T>.One; begi n if Assigned (data) then begi n

Form30.Log( 'ClassName: ' + data.ClassName); Form30.Log( 'Size: ' + IntToStr (data.InstanceSize)); Form30.Log( 'ToString: ' + data.ToString);


75 Two comments here. The first is that InstanceSize returns the actual size of the object, unlike the generic SizeOf function we used earlier, which returns the size of the reference type. Second, the ToString method is a new (relevant) Delphi 2009 method of TObj ect that I'll cover in details in Chapter 7, in the section "TObjects's New Methods".

You can play with the program to see its actual effect, as it defines and uses a few instances of the generic type, as in the following code snippet: var samplel: TSampleClass<TButton>; begi n samplel := TSampleClass<TButton>.Create; try samplel.SetT (Sender as TButton); samplel.One; fi nal ly samplel.Free; end;

Notice that by declaring a class with a customized ToString method, this custom version will get called when the data object is of the specific type, regardless of the actual type provided to the generic type. In other words, if you have a TButton descendant like:

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment