有时我们需要一个可选参数
function doSomething(foo:Integer; bar:TObject=nil)
begin
if bar <> nil then // do something optional with bar
....
end
如何使用 bool 值进行等效操作,以区分两个 bool 值和“无值”?
function doSomething(foo:Integer; bar:Boolean=nil) // Won't compile
begin
if bar <> nil then // do something optional with bar
end
显然这不会编译,因为 bool 值不能为零。
基本上,我想要一个具有三种可能状态的参数;正确、错误或“未指定”。
最佳答案
您可以通过其他方式使用重载来做到这一点:
function doSomething(foo:Integer): Boolean; overload;
begin
// do something without bar
end;
function doSomething(foo:Integer; bar:Boolean): Boolean; overload
begin
// do something optional with bar
end;
然后您可以将其用作 doSomething(1)
以及 doSomething(1, true)
使用您的示例,它将相当于:
function doSomething(foo:Integer; bar:Boolean=nil): Boolean; // Won't compile
begin
if bar <> nil then
// do something optional with bar
else
// do something without bar
end;
关于delphi - 传递一个可选的 bool 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7508664/