我刚刚写了一个非常简单的类来测试 Delphi XE8 中的 TDictionary<> 类。
当我尝试显示我添加的记录时,它给我带来了访问冲突错误,我不明白为什么?
这是我的课
unit Unit3;
interface
uses
Classes, System.SysUtils, System.Types, REST.Types, System.JSON, Data.Bind.Components,
System.RegularExpressions, System.Variants,
Generics.Collections, FMX.Dialogs {$IFDEF DEBUG}, CodeSiteLogging{$ENDIF};
type
TAArray2 = class;
PTRec=^TRec;
TRec = class
public
Key : Variant;
isRequired : boolean;
Value : Variant;
OldValue : Variant;
JSON : string;
Items : TAArray2;
procedure Add(Key : Variant ; Value: TRec);
end;
TAArray2 = class(TDictionary<Variant, TRec>)
private
function Get(Index: variant): TRec;
public
destructor Destroy; override;
procedure Add(Key : Variant ; Value: TRec);
property Items[Cle : Variant]: TRec read Get; default;
end;
implementation
procedure TRec.Add(Key : Variant ; Value: TRec);
begin
if not(assigned(items)) then
self.Items := TAArray2.Create;
Items.Add( Key, Value);
showmessage(inttostr(items.Count)); // this show 1 means items is instanciate and contain the proper data
end;
function TAArray2.Get(Index: Variant): TRec;
begin
Result := inherited items[Index]
end;
end.
然后我正在使用此代码对其进行测试:(带有 1 个 TButton 和 1 个 TMemo 的表单)
procedure TForm1.ShowAssocArray2(AAA : TAArray2 ; Level : integer);
var
s : string;
MyRec : TRec;
begin
for MyRec in AAA.Values Do
begin
FillChar(s, Level * 4, ' ');
memo1.Lines.Add(s + string(MyRec.Key) + ' = ' + string(MyRec.Value));
if MyRec.Items.Count > 0 then // ERROR HERE
ShowAssocArray2(MyRec.items, Level + 1); // recursive for childrens
end;
end;
procedure TForm1.Button4Click(Sender: TObject);
var
MyList : TAArray2;
MyRec : TRec;
i : Integer;
begin
MyList := TAArray2.Create;
for i := 0 to 9 do
begin
MyRec := TRec.Create;
MyRec.Value := 'Value_' + inttostr(i);
MyRec.Key := 'No_' + inttostr(i);
MyList.Add(MyRec.Key, MyRec);
end;
// subitem
MyRec := TRec.Create;
MyRec.Value := 'test' + inttostr(i);
MyRec.Key := 'test' + inttostr(i);
MyList.Items['No_3'].Add('Extra', MyRec);
memo1.Lines.Add('Nb of Record : ' + inttostr(MyList.Count));
ShowAssocArray2(MyList, 0);
end;
我尝试了很多方法:MyRec.Items.Count 或 MyRec.Values.Count 或 MyRec.Items.Values.count ......我总是有一个错误,我不明白为什么?