$theTitle=wp_title(" - ", false); if($theTitle != "") { ?>
About Virtualization, VDI, SBC, Application Compatibility and anything else I feel like
2 Mar // php the_time('Y') ?>
For my Terminal Server unit in the Jedi Security library I use 2 TObjectList descendants to hold a list of Terminal Server Sessions and Processes. Consider the sample below which connects to a server and enumerates all sessions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | var ATerminalServer: TJwTerminalServer; i: Integer; begin ATerminalServer := TjwTerminalServer.Create; ATerminalServer.Server := 'TS001'; try if ATerminalServer.EnumerateSessions then begin // Now loop through the list for i := 0 to ATerminalServer.Sessions.Count - 1 do begin Memo1.Lines.Add(ATerminalServer.Sessions[i].Username); end; end; except on E: EJwsclWinCallFailedException do begin // Handle Exception here end; end; // Free Memory ATerminalServer.Free; end; |
In the sample I loop through the sessions with a for loop. Even though Delphi supports the for in loop since Delphi 2005 it’s not possible to use this in TObjectList descendants, so we cannot use this:
1 2 3 4 5 | // Now loop through the list for Session in ATerminalServer.SessionList do begin Memo1.Lines.Add(Session.Username); end; |
To make this possible we need to implement GetEnumerator and an Enumerator class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | TJwSessionsEnumerator = class private FIndex: Integer; FSessions: TJwWTSSessionList; public constructor Create(ASessionList: TJwWTSSessionList); function GetCurrent: TJwWTSSession; function MoveNext: Boolean; property Current: TJwWTSSession read GetCurrent; end; constructor TJwSessionsEnumerator.Create(ASessionList: TJwWTSSessionList); begin inherited Create; FIndex := -1; FSessions := ASessionList; end; function TJwSessionsEnumerator.GetCurrent; begin Result := FSessions[FIndex]; end; function TJwSessionsEnumerator.MoveNext: Boolean; begin Result := FIndex < FSessions.Count - 1; if Result then Inc(FIndex); end; |
Now we add a function with the name GetEnumerator in the SessionList class:
1 2 3 4 | function TJwWTSSessionList.GetEnumerator: TJwSessionsEnumerator; begin Result := TJwSessionsEnumerator.Create(Self); end; |
And that’s really all!
One Response for "Supporting for in loop in TObjectList descendants"
[…] Go and learn more about it here. […]
Leave a reply