简体   繁体   English

Delphi:引用参数的泛型类型推断

[英]Delphi: Generic type inference of reference argument

What's the best way to get around the shortcoming of generic type inferencing of reference arguments, so that I don't have to specify the type in every call ? 克服引用参数的泛型类型推断的缺点的最佳方法是什么, 这样我就不必在每次调用中都指定类型

Update : I don't mind other (including non-generic) solutions as long as it works with multiple (any?) types. 更新 :我不介意其他(包括非通用)解决方案,只要它适用于多种(任何?)类型。

This seems to still not have been resolved, although known for quite some time. 尽管已经有相当长的一段时间了,但这似乎仍未解决。

Please vote for a resolution to this on Embarcaderos Quality Central: Issue #78103 . 请在Embarcaderos Quality Central: 问题#78103上对此问题进行投票

From a comment by Barry Kelly to Generic Methods and Type Inferencing : 评论巴里·凯利泛型方法和类型推断

PS: Your example, in Tiburon, almost works. PS:您的例子在Tiburon中几乎可行。 Method type inference works well for arguments passed by value. 方法类型推断对于按值传递的参数非常有效。 It doesn't work for arguments passed by reference, unfortunately (the compiler is being too strict). 不幸的是,它不适用于通过引用传递的参数(编译器过于严格)。

Now, almost three years later, I'm trying the same thing in Delphi XE, and it complains that: 现在,差不多三年后,我正在Delphi XE中尝试相同的操作,它抱怨说:

[DCC Error] INIv1_Parser.pas(81): E2033 Types of actual and formal var parameters must be identical [DCC错误] INIv1_Parser.pas(81):E2033实际和形式var参数的类型必须相同

When calling: 致电时:

function FindDataItemValue<T>(ItemType: TDataItemType; out Value: T): Boolean;

With: 附:

var MaxG: Real;
...
if Data.FindDataItemValue(PAR_MaxG, MaxG) and (MaxG = 2.5) then ...

Commonly suggested work-around : However, if I add the generalization on the call, it works fine; 普遍建议的解决方法 :但是,如果在调用中添加泛化,则可以正常工作; although annoying that it is even needed. 尽管很烦,甚至需要它。

Update : 更新

Thus far, The best I've come up with is to use either Variants or the TValue record from the Rtti module. 到目前为止,我想出的最好办法是使用Variants或Rtti模块中的TValue记录。 Using variants I implement interfaces when I need to use objects, and store a reference to that (interface) in the variant. 使用变体我需要使用对象时实现接口,并在变体中存储对该接口的引用。

Type inference does not currently work for var and out parameters. 类型推断目前不适用于var和out参数。 I agree that it is highly annoying. 我同意这很烦人。

There is no workaround. 没有解决方法。 You have to specify the type. 您必须指定类型。

var
  MaxG: Real;
...
  if Data.FindDataItemValue<Real>(PAR_MaxG, MaxG) and (MaxG = 2.5) then ...

If you want Embarcadero to resolve this, then vote for this QC entry that is about your issue . 如果您希望Embarcadero解决此问题,请投票给您有关问题的QC条目

The QC entries with the highest votes get more attention. 质量最高的QC条目获得更多关注。

最好的方法是完全按照您引用的文章中的说明进行操作:在方法调用中包括类型参数:

if Data.FindDataItemValue<Real>(PAR_MaxG, MaxG) ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM