【问题标题】:How to passing a nil value in a in parameter of procedure of object type如何在对象类型过程的 in 参数中传递 nil 值
【发布时间】:2011-07-06 21:16:25
【问题描述】:

我想在声明为procedure of object的参数中传递一个零值

考虑这段代码

案例一

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;

案例 3

我还发现如果删除 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;

问题是How i can pass the nil value as parameter? 使用案例 1 中的代码?

【问题讨论】:

  • 你为什么要检查@foo &lt;&gt; nil?一个简单的Assigned(Foo) 避免了否定,而Assigned 通常建议用于检查指针和方法引用。

标签: delphi delphi-2007 delphi-xe


【解决方案1】:

将 nil 类型转换为 TFooProc:

DoSomething(Param1, TFooProc(nil));

【讨论】:

  • 感谢@Sertac 的解决方法,您知道这种delphi 编译器行为的原因吗?
  • @Salvador - 不完全是,当出现重载时,编译器会寻找更严格的匹配,即“nil”似乎更自然地匹配“指针”(pchar , 类型等..)。
  • 无论如何,这肯定看起来像是编译器中的一个小故障。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-18
  • 1970-01-01
  • 1970-01-01
  • 2011-11-05
  • 1970-01-01
  • 2011-07-27
  • 2015-08-03
相关资源
最近更新 更多