我有一个这样的对象:
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;
要访问FObjList的值,我想写:
for tmpObject in MyObj.Values do
...
我如何声明属性“Values”,以便MyObj.Values的行为就像我访问MyObj.FObjList.Values一样?
答案 0 :(得分:3)
/// 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;
答案 1 :(得分:1)
TValueCollection是TDictionary的嵌套类,必须是合格的。最好为Values指定一个getter方法。
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;
编辑:Ups!太晚了......但略有不同。