Delphi代码中这个与对象数组函数相关的代码能否做得更简洁?

问题描述 投票:1回答:1

关于Delphi中的这个函数。

function TAudioFileMetadata.LoadTags(const Filename: String; var LastError: Integer; var DetectedFormat: TAudioFormat): Boolean;
type
  TLoadFromFunction = function (const Filename: String; var LastError: Integer): Boolean of object;

  TLoadFrom = record
    Format: TAudioFormat;
    Process: TLoadFromFunction;
  end;

var
  i: Byte;
  LoadOrder: array [1..6] of TLoadFrom;

begin
  DetectedFormat := afUnknown;

  LoadOrder[1].Format := afMp3;
  LoadOrder[1].Process := LoadFromMp3;

  //...

  LoadOrder[6].Format := afApe;
  LoadOrder[6].Process := LoadFromApe;

  for i := Low(LoadOrder) to High(LoadOrder) do
  begin
    Result := LoadOrder[i].Process(Filename, LastError);
    if Result then
    begin
      DetectedFormat := LoadOrder[i].Format;
      break;
    end;
  end;
end;

如何改进我的实现?我能否在Delphi中创建一个填充的函数?LoadOrder 数组的一次拍摄(或至少不使用每行2行的 TLoadFrom)? 是否可以 const 数组(我不这么认为)?

arrays pointers delphi
1个回答
3
投票

Delphi闭包 (function|procedure ... of object)的支持。TMethod 记录,你可以在运行时对其进行操作。所以可以试试这样的方法。

function TAudioFileMetadata.LoadTags(const Filename: String; var LastError: Integer; var DetectedFormat: TAudioFormat): Boolean;
type
  TLoadFromFunction = function (const Filename: String; var LastError: Integer): Boolean of object;

  TLoadFrom = record
    Format: TAudioFormat;
    ProcessAddr: Pointer;
  end;

const
  LoadOrder: array[1..6] of TLoadFrom = (
    (Format: afMp3; ProcessAddr: @TAudioFileMetadata.LoadFromMp3),
    ...
    (Format: afApe; ProcessAddr: @TAudioFileMetadata.LoadFromApe)
  );

var
  i: Byte;
  Process: TLoadFromFunction;

begin
  DetectedFormat := afUnknown;
  TMethod(Process).Data := Self;

  for i := Low(LoadOrder) to High(LoadOrder) do
  begin
    TMethod(Process).Code := LoadOrder[i].ProcessAddr;

    Result := Process(Filename, LastError);
    if Result then
    begin
      DetectedFormat := LoadOrder[i].Format;
      Exit;
    end;
  end;
end;
© www.soinside.com 2019 - 2024. All rights reserved.