我需要实现控件的TList后代+额外的对象 类似的东西:
List.Add(AControl, AObject)
因此,列表将同时包含AControl, AObject
使用Delphi 7执行此操作的最佳方法是什么?
答案 0 :(得分:10)
您可以存储记录列表,然后您可以将任何您想要的内容放入记录中,例如:
type
PMyRecord = ^MyRecord;
MyRecord = record
Control: TControl;
Object: TObject;
end;
var
Rec: PMyRecord;
begin
New(Rec);
try
Rec.Control := AControl;
Rec.Object := AObject;
List.Add(Rec);
except
Dispose(Rec);
Raise;
end;
end;
var
Rec: PMyRecord;
begin
Rec := PMyRecord(List[SomeIndex]);
// use Rec.Control and Rec.Object as needed...
end;
从列表中删除项目时,不要忘记Dispose()
项目:
var
Rec: PMyRecord;
begin
Rec := PMyRecord(List[SomeIndex]);
List.Delete(SomeIndex);
Dispose(Rec);
end;
此外,当您使用完列表时,或者至少在您使用Clear()
时:
var
I: Integer;
Rec: PMyRecord;
begin
for I := o to List.Count-1 do
Dispose(PMyRecord(List[I]));
//...
end;
如果从TList
派生新类,则可以覆盖其虚拟Notify()
方法来处置项目:
type
TMyList = class(TList)
protected
function Get(Index: Integer): PMyRecord;
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
public
function Add(AControl: TControl; AObject: TObject): Integer;
procedure Insert(Index: Integer; AControl: TControl; AObject: TObject);
property Items[Index: Integer]: PMyRecord read Get; default;
end;
function TMyList.Add(AControl: TControl; AObject: TObject): Integer;
var
Rec: PMyRecord;
begin
New(Rec);
try
Rec.Control := AControl;
Rec.Object := AObject;
Result := inherited Add(Rec);
except
Dispose(Rec);
Raise;
end;
end;
procedure TMyList.Insert(Index: Integer; AControl: TControl; AObject: TObject);
var
Rec: PMyRecord;
begin
New(Rec);
try
Rec.Control := AControl;
Rec.Object := AObject;
inherited Insert(Index, Rec);
except
Dispose(Rec);
Raise;
end;
end;
function TMyList.Get(Index: Integer): PMyRecord;
begin
Result := PMyRecord(inherited Get(Index));
end;
procedure TMyList.Notify(Ptr: Pointer; Action: TListNotification);
begin
inherited;
if Action = lnDeleted then
Dispose(PMyRecord(Ptr));
end;
答案 1 :(得分:1)
试试这个
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TMyContainer = class
public
ctnGen: TControl;
objGen: TObject;
constructor Create(const ctnGen: TControl; const objGen: TObject);
end;
var
Form1: TForm1;
implementation
uses
Contnrs;
{$R *.DFM}
{ TMyContainer }
constructor TMyContainer.Create(const ctnGen: TControl;
const objGen: TObject);
begin
inherited Create();
Self.ctnGen := ctnGen;
Self.objGen := objGen;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
lstGen: TObjectList;
begin
lstGen := TObjectList.Create(True);
try
lstGen.Add(TMyContainer.Create(Self, Self));
ShowMessage(TMyContainer(lstGen.Items[0]).objGen.ClassName);
finally
lstGen.Free;
end;
end;
TObjectList将释放TMyContainer类