2006. augusztus 8., kedd

Default Array Properties


Problem/Question/Abstract:

By using default array properties, you can abbreviate your calls by using the syntax Class[I] as opposed to Class.Items[I].

Answer:

Delphi supports abbreviated calls to the default class array property.  This can be used in any delphi class that uses defaults such as TStringList.

For Example:

use MyStringList[Index] in place of MyStringList.Strings[Index]

This is somewhat useful for cleaning up the code, especially if you are accessing the property in question often.

To add this feature to your own classes, simply add the "default" directive (storage specifier) after the array (indexed) property you want to use as the default.

For Example:

type
  TMyGraphicList = class
  public
    property Names[Index: Integer]: string read GetName write SetName;
    property Objects[Index: Integer]: TObject read GetObj write SetObj;
    property Images[Index: Integer]: TImage read Get write set; default;
    {...}
  end;

By adding the "default" directive after the Images property we have designated the Images array property as the default.  

Access can now be abbreviated such as this:

for I := 0 to MyGraphicList.Count - 1 do
begin
  AName := MyGraphicList.Names[I];
  AObject := MyGraphicList.Objects[I];
  AImage := MyGraphicList[I]; // instead of MyGraphicList.Images[I]
end;

NOTE: There can be only one default array property for each class.  Entering a second would generate a compiler error.

IMPORTANT: "Array" properties are different than "attribute" properties, and the default directive takes on a different meaning for each.  When used on an attribute property, the default directive (storage specifier) releates to how Delphi saves the values of published properties in form (.DFM) files.

Nincsenek megjegyzések:

Megjegyzés küldése