gpt4 book ai didi

delphi - 如何安全绕过Delphi错误: "types of formal and actual parameters must be identical"

转载 作者:行者123 更新时间:2023-12-03 14:56:03 24 4
gpt4 key购买 nike

我需要一种方法来编写通用过程来作用于对象类型或其任何后代。

我的第一次尝试是声明

procedure TotalDestroy(var obj:TMyObject);

但是当将它与后代对象一起使用时

type TMyNewerObject = class(TMyObject);
var someNewerObject: TMyNewerObject;

TotalDestroy(someNewerObject);

我收到臭名昭著的错误“形式参数和实际参数的类型必须相同”

因此,在努力寻找解决方案的同时,我查看了Delphi系统FreeAndNil程序的源代码。我发现了这个很棒的声明,以及这个令人惊讶的评论

{ FreeAndNil frees the given TObject instance and 
sets the variable reference to nil.
Be careful to only pass TObjects to this routine. }

procedure FreeAndNil(var Obj);

它避免了类型检查错误,但它不使用安全网。

我的问题是...有没有安全的方法来检查无类型 var 参数的类型?

或者换句话说,你能改进这个Delphi源代码,这样就不需要警告了吗?

procedure FreeAndNil(var Obj);
var
Temp: TObject;
begin
Temp := TObject(Obj);
Pointer(Obj) := nil;
Temp.Free;
end;

最佳答案

让我们看看您想要做什么。

您想要调用一个采用 X 的方法,传入 Y 类型的对象,其中 Y 是 X 的后代。问题是,参数是“var”参数。

让我们分析一下如果可能的话您可以做什么。

type
TBase = class
end;
TDescendant = class(TBase)
end;

procedure Fiddle(var x: TBase);
begin
x := TDescendant.Create;
end;

type
TOtherDescendant = class(TBase)
end;

var a: TOtherDescendant;
a := TOtherDescendant.Create;
Fiddle(a);

呃-哦,现在a不再包含TOtherDesendant的实例,它包含TDesendant的实例。这可能会让调用后的代码感到惊讶。

您不仅要考虑您打算使用您建议的语法做什么,还要考虑您实际上可以使用该语法做什么。

您应该阅读 Eric Lipperts 关于 .NET 中类似问题的优秀博客文章,可在此处找到:Why do ref and out parameters not allow type variation? .

关于delphi - 如何安全绕过Delphi错误: "types of formal and actual parameters must be identical",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2051673/

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