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.Val开发者_如何转开发ues;
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?
/// 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;
TValueCollection is a nested class of TDictionary and has to be qualified. And you better specify a getter method for Values.
type
TMyObjectDictionary = TObjectDictionary <integer, TMyObject>;
TMyObj = class
private
FObjList: TMyObjectDictionary;
function GetValues: TMyObjectDictionary.TValueCollection;
public
property Values: TMyObjectDictionary.TValueCollection read GetValues;
end;
function TMyObj.GetValues: TMyObjectDictionary.TValueCollection;
begin
Result := FObjList.Values;
end;
Edit: Ups! Too late... But slightly different.
精彩评论