我开始学习并在我的项目中积极使用 OOP。我发现类似 LDevices.Devices[i]
的结构看起来非常麻烦并且使代码难以阅读。
所以我的问题是:有没有什么方法可以为字段创建一个快捷方式来访问它,例如 LDevices[i]
,不是LDevices.Devices[i]
? Devices
是 TObjectList<TDevice>
.
我的对象的结构,供引用:
TDeviceStorage = class (TObject)
private
DevicesByID: TDictionary<Integer,TDevice>;
public
Devices: TObjectList<TDevice>;
Constructor Create;
Destructor Destroy; override;
procedure AddDevice(aID: Integer; aName, aShortName: String; aSubtype, aLocation: Integer; aSteamID: String);
procedure Clear();
function Count(): Integer;
function DeviceByID(aID: Integer): TDevice;
function DeviceIndex(aID: Integer): Integer;
end;
最佳答案
是的,这正是 default
directive on an array property 的内容。用于:
TDeviceStorage = class(TObject)
private
FDevicesByID: TDictionary<Integer, TDevice>;
FDevices: TObjectList<TDevice>;
function GetDeviceCount: Integer;
function GetDevice(Index: Integer): TDevice;
procedure SetDevice(Index: Integer; const Value: TDevice);
public
constructor Create;
destructor Destroy; override;
procedure AddDevice(AID: Integer; const AName, AShortName: string;
ASubtype, ALocation: Integer; const ASteamID: string);
procedure Clear;
function DeviceByID(AID: Integer): TDevice;
function DeviceIndex(AID: Integer): Integer;
property Devices[Index: Integer]: TDevice read GetDevice write SetDevice; default;
property DeviceCount: Integer read GetDeviceCount;
end;
与
function TDeviceStorage.GetDevice(Index: Integer): TDevice;
begin
Result := FDevices[Index];
end;
function TDeviceStorage.GetDeviceCount: Integer;
begin
Result := FDevices.Count;
end;
procedure TDeviceStorage.SetDevice(Index: Integer; const Value: TDevice);
begin
FDevices[Index] := Value;
end;
现在,如果DS: TDeviceStorage
,您可以编写DS[i]
来访问FDevices<中的第
.i
设备
关于object - Delphi对象: shortcut for TObjectList iteration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67050444/