classdelphipropertiestobjectlist

How to create properties of classes within classes?


For Delphi XE6, I am creating a class called TAccountSearch. It has a small number of properties, and a class of TObjectList. My issue is I cannot seem to make the TObjectList class exposed as a property.

Code Snippet... Create the class I will use for TObjectList

  type
  TSearchHits = class
  ID: Integer;
  Name : String;
  ...
  end;

Now create the class which contains an instance of TObjectList...

type
  TAccountSearch = class
  private
    zSearchPhrase: string;
    zList: TObjectList<TSearchHits>;
    ...
    property SearchPhrase: string read zSearchPhrase; 
    property MyList:TObjectList<TSearchHits> read TObjectList<TSearchHits>;
end;

TAccountSearch.SearchPhrase is a valid property. TAccountSearch.MyList is not....
From the accountSearch class, How do I give the calling program access to SearchHits as a Property? Second, if I don't include a WRITE definition on the PROPERTY line, the property is considered read only.
Is that accurate? Is that the proper way to make read only properties?


Solution

  • You access the instance variable zList in order to gain access to the internal storage:

    property MyList: TObjectList<TSearchHits> read zList write zList;
    

    Use write SetMyList if you need a setter procedure.

    You can use a getter function as well to gain access:

    private
      function GetMyList: TObjectList<TSearchHits>;
    published
      property MyList: TObjectList<TSearchHits> read GetMyList write SetMyList;
    

    where the getter function would be written something like

    function TAccountSearch.GetMyList: TObjectList<TSearchHits>;
    begin
      Result := zList;
    end;
    

    The way to implement read-only properties is simply to omit the write portion.

    property MyList: TObjectList<TSearchHits> read zList;