如何在对象类型的过程的输入参数中传递nil值

8

我希望在一个声明为procedure of object的参数中传递一个空值。

考虑以下代码:

情况1

type
  TFooProc = procedure(Foo1, Foo2 : Integer) of object;


procedure DoSomething(Param1:Integer;Foo:TFooProc);overload;
var
  a, b : Integer;
begin
   a:=b*Param1;
   //If foo is assigned
   if @Foo<>nil then
    Foo(a, b);
end;

procedure DoSomething(Param1:Integer);overload;
begin      
  DoSomething(Param1,nil);//here the delphi compiler raise this message [DCC Error] E2250 There is no overloaded version of 'DoSomething' that can be called with these arguments
end;

案例2

我发现,如果我将TFooProc声明为procedure类型,则代码可以编译。(但在我的情况下,我需要一个procedure of object类型)

type
  TFooProc = procedure(Foo1, Foo2 : Integer);


procedure DoSomething(Param1:Integer;Foo:TFooProc);overload;
var
  a, b : Integer;
begin
   a:=b*Param1;
   //If foo is assigned
   if @Foo<>nil then
    Foo(a, b);
end;

procedure DoSomething(Param1:Integer);overload;
begin
  DoSomething(Param1,nil);
end;

案例三

我还发现,如果删除overload指令,则代码可以编译成功。

type
  TFooProc = procedure(Foo1, Foo2 : Integer) of object;


procedure DoSomething(Param1:Integer;Foo:TFooProc);
var
  a, b : Integer;
begin
   a:=b*Param1;
   //If foo is assigned
   if @Foo<>nil then
    Foo(a, b);
end;

procedure DoSomething2(Param1:Integer);
begin
  DoSomething(Param1,nil);
end;

问题是如何将空值作为参数传递?以便在第一种情况下使用代码?请参考以下内容:

如何将nil值作为参数传递?以使得在第一种情况下可以使用该代码?


1
为什么要检查 @foo <> nil?简单的 Assigned(Foo) 可以避免否定,并且通常建议使用 Assigned 来检查指针和方法引用。 - Marjan Venema
1个回答

13
将nil强制转换为TFooProc类型:
DoSomething(Param1, TFooProc(nil));

谢谢@Sertac提供的解决方法,你知道这个Delphi编译器行为的原因吗? - Salvador
@Salvador - 不完全是这样,当有重载时,编译器会寻找更严格的匹配,即'nil'似乎更自然地匹配'pointer'(pchar、type等)。 - Sertac Akyuz
无论如何,这肯定看起来像编译器中的故障。 - Sertac Akyuz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接