gpt4 book ai didi

Delphi:获取调用者函数的UnitName

转载 作者:行者123 更新时间:2023-12-04 01:58:05 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com