【问题标题】:How to pass "nil" constant to the untyped parameter?如何将“nil”常量传递给无类型参数?
【发布时间】:2011-11-05 23:00:42
【问题描述】:

是否可以将 nil 作为未声明的常量传递给某个函数的无类型参数? 我有这样的函数,我想将一些常量传递给Data 参数以满足编译器的要求。在内部,我由 Size 参数决定。我知道我可以使用 Pointer 而不是无类型参数,但它对我的情况来说更舒服。

现在我收到E2250 There is no overloaded version of 'RS232_SendCommand' that can be called with these arguments

function RS232_SendCommand(const Command: Integer): Boolean; overload;
begin
  // is it possible to pass here an undeclared constant like nil in this example?
  Result := RS232_SendCommand(Command, nil, 0);
end;

function RS232_SendCommand(const Command: Integer; const Data; const Size: Integer): Boolean; overload;
begin
  ...
end;

这可行,但如果我可以保留变量声明,我会很高兴。

function RS232_SendCommand(const Command: Integer): Boolean; overload;
var
  Nothing: Pointer;
begin
  Result := RS232_SendCommand(Command, Nothing, 0);
end;

解决方案是使用这样的东西。

function RS232_SendCommand(const Command: Integer): Boolean; overload;
begin
  // as the best way looks for me from the accepted answer to use this
  Result := RS232_SendCommand(Command, nil^, 0);

  // or it also possible to pass an empty string constant to the untyped parameter
  // without declaring any variable
  Result := RS232_SendCommand(Command, '', 0);
end;

我这样做是因为我的一些命令在命令传输后发送了数据。

感谢您的帮助

【问题讨论】:

    标签: delphi untyped-variables


    【解决方案1】:

    不,你不能。 我不知道

    无类型参数

    声明时可以省略类型说明 varconstout 参数。 (必须键入值参数。)对于 示例:

    procedure TakeAnything(const C);

    声明一个名为 TakeAnything 接受任何类型的参数。当你这样称呼 例程,您不能将数字或无类型的数字常量传递给它。

    发件人:Parameters (Delphi)

    所以,也许添加另一个没有 const arg 的重载版本,您可以在 Size = 0 时调用它。

    【讨论】:

    • 谢谢。这对我帮助很大。从you cannot pass it a numeral or untyped numeric constant这句话我找到了办法,一个空字符串常量:Result := RS232_SendCommand(Command, '', 0);
    【解决方案2】:

    简单:

    RS232_SendCommand(Command, nil^, 0);
    

    您只需要确保您没有从RS232_SendCommand 内部访问 Data 参数,但大概这就是 0 大小参数的用途。

    在我看来,这是最好的解决方案,因为它非常明确地表明您正在传递无法访问的东西。

    【讨论】:

    • 哇,这更聪明。我至少会接受这个作为答案,因为有人提到这是不可能的。谢谢
    • 我不确定nil^ 是否可以归类为优雅! ;-) 你只需要记住这不会取消引用 nil 指针。
    猜你喜欢
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 2015-11-02
    相关资源
    最近更新 更多