Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement indexed [] default property

Tags:

class

delphi

I have a class which holds multiple filenames inside a TStringList. I can access a particular filename by index using:

myclass.stringlistclass[index]

But how can I get an filename using the following syntax?

myclass[index]

Is there a property I can implement to achieve this functionality?

like image 416
opc0de Avatar asked May 29 '12 09:05

opc0de


2 Answers

private
  function GetColumnValue(const ColumnName: string): string; overload;
  function GetColumnValue(Index: Integer): string; overload;
  procedure SetColumnValue(Index: integer; const Value: string);
public
  property Values[const ColumnName: string]: string read GetColumnValue; default;
  property Values[ColumnIndex: integer]: string read GetColumnValue write SetColumnValue; default;
end;

This means:

  • you can have multiple default indexor properties
  • the multiple indexor properties can have the same name e.g., Values
  • the properties getters can be overloads (i.e. have the same name) e.g., GetColumnValue
  • Delphi will resolve the overloads by type signature
like image 99
Marck Avatar answered Sep 21 '22 18:09

Marck


Use "default" keyword on the indexed property. There can be one default property per class.

You can have multiple default properties per class, however these default properties must have the same name.

An example:

    property Item[const Coordinate: TPoint]: TSlice read GetSlice write SetSlice; default;
    property Item[x,y: integer]: TSlice read GetSlice write SetSlice; default; 

You can even have the getters and setters share the same name, as long as they have the overload directive.

like image 21
Eugene Mayevski 'Callback Avatar answered Sep 19 '22 18:09

Eugene Mayevski 'Callback