Delphi:获取调用者函数的UnitName

标签 delphi

unit MyFirstUnit;
  uses MyTranslateUnit;
  ...
  sText := Dictionary('text to translate', UnitName);
  ...
end.
unit AnotherUnit;
  uses MyTranslateUnit;
  ...
  sText := Dictionary('new text to translate', UnitName);
  ...
end.
unit MyTranslateUnit;
  function Dictionary(sTextToTranslate: string; sUnitName: string)
  begin
    // Here I need the UnitName of the caller
    Result := ...
  end;
end.

我的程序中有很多地方我调用字典(...) .如何避免将 UnitName 作为第二个参数传递?
是否可以在没有第二个参数的情况下在 MyTranslateUnit 中获取调用者的 UnitName?

我想要一个像

function Dictionary(sTextToTranslate: string)

最佳答案

只要调用发生在类的方法内部,你就可以简单地写 UnitName .每一个德尔福TObject提供 class function UnitName: string;它给出了类在其中声明的单元的名称。

这不会给您省略第二个参数的可能性,但它简化了单元重命名或代码在单元之间复制或移动时的维护。

编辑:有一个真正肮脏的技巧可以在没有第二个参数的情况下完成这项工作,并且它也只能在类的方法中工作。我建议仅将其用作最后的手段!删除一个参数的好处很容易在 future 适得其反。

为 TObject 声明一个类助手,如下所示:

type
  TRealDirtyDontDoItObjectHelper = class helper for TObject
  public
    class function Dictionary(const sTextToTranslate: string): string;
  end;

implementation

class function TRealDirtyDontDoItObjectHelper.Dictionary(const sTextToTranslate: string): string;
begin
  { whatever implementation should go here }
  Result := UnitName + ': ' + sTextToTranslate;
end;

现在你可以调用类似的东西
Caption := Dictionary('title');

在任何方法中,其中 UnitName给出方法所属类的声明单元。请注意,这意味着当前实例的类,而不一定是声明方法的某个继承类。

我还应该提到,TObject 的这个类助手不会干扰任何其他类的类助手,即使这些显然是从 TObject 继承的。 .

关于Delphi:获取调用者函数的UnitName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49274168/

相关文章:

android - Delphi AndroidAPI 运动检测

image - Delphi PNG图像在移动/加载图像时显示矩形BUG

delphi - 在 Delphi/FreePascal 中解析电子邮件时间戳

delphi - 使用 MSBuild 编译 Delphi 2010 项目

delphi - 每个成功的 HTTP 请求是否总是返回状态码 200?

delphi - 如何模拟没有虚拟方法的类?

Delphi ADO 对来自 SQL Server 的十进制值进行四舍五入

delphi - 使用 Gold Parser 解析项目和包文件 - 需要 'IdList' 的帮助

multithreading - 是否有必要在Delphi中对 bool 属性进行多线程保护?

delphi - TRzDirectoryTree设置当前目录