object - Delphi对象: shortcut for TObjectList iteration

标签 object oop delphi iteration delphi-10.4-sydney

我开始学习并在我的项目中积极使用 OOP。我发现类似 LDevices.Devices[i] 的结构看起来非常麻烦并且使代码难以阅读。

所以我的问题是:有没有什么方法可以为字段创建一个快捷方式来访问它,例如 LDevices[i] ,不是LDevices.Devices[i]DevicesTObjectList<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/

相关文章:

php - 如何通过静态方法在其父类中使用子类中的静态变量

c# - 当其中一个实现需要更多数据时该怎么办

java - 实现接口(interface)的不同对象的列表

javascript - 向现有 javascript 对象添加新属性

java - 仅更改 ioc 容器中大型依赖关系图中的一个依赖关系以进行测试

delphi - 将上下文菜单添加到 TPageControl 的选项卡

json - 如何将 Delphi XE 10 中的 JSON 字符串返回的日期时间解析为 TDateTime

delphi - 如何防止滚动框中的控件跳入焦点?

java - scala 类中的 println 不会在 STDOUT 上显示输出

swift - 为什么我有我的子类的方法?