Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property using Generics in Delphi

I'm trying to write a property which uses generics:

type TMyClass = class
  protected
    function GetCountBy<T: Class>: Integer;
  public
    property CountBy<T: Class>: Integer read GetCountBy<T>;
  end;

but the compile fails on the property declaration with the message 'Property CountBy does not exist in base class', and the red squiggle on the opening < of the property name.

Is there any way to achieve this?

Edit: Here's my other use case, which is more complex but more real world:

property ItemsBy<T: Class>[Index: Integer]: T read GetItemsBy<T> write SetItemsBy<T>;

The function filters the contents of a list to return the Index'th item of the specified class.

like image 750
Mike Sutton Avatar asked Jun 05 '12 19:06

Mike Sutton


2 Answers

Generic properties are not supported in Delphi. Only generic classes, or generic methods.

I can't find anything in the documentation that explicitly states that limitation. On the other hand the documentation only describes generic classes and generic methods. And the new language grammar to support generics also makes no mention of properties.

like image 200
David Heffernan Avatar answered Oct 11 '22 00:10

David Heffernan


I'm not up to speed on generics but shouldn't the declaration be more like this

  type TMyClass<T: class> = class
  protected
    function GetCountBy<T>: Integer;
  public
    property CountBy<T>: Integer read GetCountBy<T>;
  end;
like image 1
Lieven Keersmaekers Avatar answered Oct 11 '22 02:10

Lieven Keersmaekers