Search code examples
delphigenericsdelphi-2009

How to make TObjectDictionary.Values accessible as property?


I have an object like this:

  TMyObj = class
  private
    FObjList: TObjectDictionary <integer, TMyObject>;
  public
    constructor Create;
    destructor Destroy;
    // How to access Values correctly? Something similar to this not working code
    property Values: TValueCollection read FObjList.Values write FObjList.Values;
  end;

  var MyObj: TMyObj;

To access the values of FObjList, I'd like to write:

  for tmpObject in MyObj.Values do
...

How do I need to declare the property "Values" so that MyObj.Values behaves exactly as if I would access MyObj.FObjList.Values?


Solution

  •   /// Interface
    
      TMyDictionary = TObjectDictionary <integer, TMyObject>;
      TMyValueCollection = TDictionary<integer,TMyObject>.TValueCollection;
    
      TMyObj = class
      private
        FObjList: TMyDictionary;
        function GetValues: TMyValueCollection;
      public
        constructor Create;
        destructor Destroy; override;
        property Values: TMyValueCollection read GetValues;
      end;
    
    
    /// Implementation
    
    
    constructor TMyObj.Create;
    begin
      inherited;
      FObjList := TMyDictionary.Create;
    end;
    
    destructor TMyObj.Destroy;
    begin
      FObjList.Free;
      inherited;
    end;
    
    function TMyObj.GetValues: TMyValueCollection;
    begin
      Result := FObjList.Values;
    end;