I knew how to do this but forgot again... Quite irritating, because I'm working on a class that contains a list of XML files, and now I just want to use a for-in loop to walk through all files in this list. This is the class I have right now:
type
TXmlFileList = class( TInterfacedObject )
private
type
TItem = class( TInterfacedObject )
strict private
FCaption: string;
protected
constructor Create( const ACaption: string; const AXML: WideString );
public
destructor Destroy; override;
property Caption: string read FCaption;
end;
strict private
FXmlFiles: array of TXmlFileList.TItem;
strict protected
function GetXmlFile( index: Integer ): TXmlFileList.TItem;
public
constructor Create( );
destructor Destroy; override;
function Add( const ACaption: string; const AXML: WideString ): Integer; overload;
function Add( const AFilename: string ): Integer; overload;
function Count: Integer;
procedure Clear;
property XmlFile[ index: Integer ]: TXmlFileList.TItem read GetXmlFile; default;
end;
Looks funny? :-) I know, but I want to hide the definition of the TXmlFile class to the outside world. Basically, the TXmlFileList class allows me to simply refer to XmlFileList[I] to get the file at position I. Works nicely.
But now I want to loop through the TXmlFileList.TItem elements, so I have to expose the TXmlFileList.TItem class. It's not enough, though. It needs an enumerator too in the TXmlFileList class!
How to create that enumerator?
You're probably wondering why I use this complex construction. Well, it might be complex but it will be used by some other developers and I don't want to provide more methods than they need. This way, I only give them the methods "Add", "Clear" and "Count" to loop through the list, and any property defined on the TItem itself. They don't need more than this, although I might add a few more features later on...