Delphi 中的无类型/无类型参数
像 TStringStream 类中没有类型的参数是什么类型:
function Read(var Buffer; Count: Longint): Longint; override;
Buffer 参数的类型是什么(它是 Pointer 类型吗?)。
What type are parameters without type like in the class TStringStream:
function Read(var Buffer; Count: Longint): Longint; override;
What is the type of Buffer parameter (is it a type of Pointer ?).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
几年前我写了一篇关于这个主题的文章:
非类型化参数在几种情况下使用;您询问的
TStream.Read
方法与我写的Move
过程最匹配。这是摘录:对于
TStream.Read
,源是流的内容,因此您不会将其作为参数传递,但目标是中所示的Buffer
参数的问题。您可以为该参数传递您想要的任何变量类型,但这意味着您需要小心。确保流的内容确实是您提供的参数类型的有效值是您的工作,而不是编译器的工作。请阅读我的文章的其余部分,了解 Delphi 使用非类型化参数的更多情况。
I wrote an article about this very topic a few years ago:
Untyped parameters are used in a few situations; the
TStream.Read
method you ask about most closely matches with theMove
procedure I wrote about. Here's an excerpt:In the case of
TStream.Read
, the source is the stream's contents, so you don't pass that in as a parameter, but the destination is theBuffer
parameter shown in the question. You can pass any variable type you want for that parameter, but that means you need to be careful. It's your job, not the compiler's, to ensure that the contents of the stream really are a valid value for the type of parameter you provide.Read the rest of my article for more situations where Delphi uses untyped parameters.
查看 Delphi 帮助中的“无类型参数”。
您可以传入任何类型,但必须在实现中对其进行强制转换。帮助表明您不能向其传递数字或无类型数字常量。所以基本上你必须知道需要什么类型,而编译器无法帮助你,所以你需要一个充分的理由来这样做。我想如果您需要该方法来处理不兼容的类型,那么它可能很有用,但是您可以为每个预期类型编写几个重载版本,我建议将其作为更好的解决方案。
Check out the Delphi help for "Untyped parameters"
You can pass in any type, but you have to cast it in the implementation. Help says that you cannot pass it a numeral or untyped numeric constant. So basically you have to be know what type to expect, and compiler can not help you, so you need a good reason to do it this way. I suppose it could be of use if you need the method to handle incompatible types, but then again you could write several overloaded versions for each expected type, I would suggest that as a better solution.
也许令人惊讶的是,将取消引用的指针作为无类型参数传递是合法的。而且指针本身甚至不必有类型。
当然,如果 SomeMethod() 的参数是一个指针,那么可能会更容易,但这可能不受您的控制。
Perhaps surprisingly, it is legal to pass a dereferenced pointer as an untyped parameter. And the pointer itself doesn't even have to have a type.
Of course it would probably have been easier if the parameter to SomeMethod() had been a pointer, but this might not be under your control.
参数列表中的
var
是 通过引用调用。它可以键入,例如Listview 的OnChanging 处理程序中的AllowChange 参数:或非键入,如您的示例中所示。
var
in a parameter list is the Delphi syntax for call by reference. It can be typed as e.g. the AllowChange parameter in the OnChanging handler of an Listview:or untyped as in your example.