简体   繁体   English

通用方法类型推断

[英]Generic methods type inference

Let's say I have a class with two generic methods: 假设我有一个带有两个通用方法的类:

TMyClass = class
  procedure DoWith<T: class> (obj: T);
  procedure DoFor<T: class> ( proc: TProc<T> );
end;

Now, when I want to call either of these two methods with a specific type parameter, Delphi can infer the type for the DoWith method, so I can call it with either 现在,当我想使用特定的类型参数调用这两种方法时,Delphi可以推断DoWith方法的类型,因此我可以使用任一方法进行调用

MyClass.DoWith <TButton> ( MyButton )

or 要么

MyClass.DoWith ( MyButton )

The Delphi Compiler will happily compile both. Delphi编译器将很高兴地同时编译两者。 But if I omit the type parameter in the DoFor method, the Delphi compiler complains about the missing type parameter: 但是,如果我在DoFor方法中省略了type参数,则Delphi编译器会抱怨缺少type参数:

MyClass.DoFor<TButton>(procedure (Button: TButton) begin .... end);  // compiles


MyClass.DoFor(procedure (Button: TButton) begin .... end);  // doesn't compile

Now my question is: Is this just a shortcoming of the compiler, or is there any logical reason (that I haven't figured out yet) that prohibits the compiler from correctly inferring the type for the DoFor method? 现在我的问题是:这仅仅是编译器的一个缺点,还是有任何逻辑原因(我还没有弄清楚)禁止编译器正确推断DoFor方法的类型?

The reason it cannot infer T from a TProc<T> argument is that at that time TProc<TButton> is a constructed type without any information that it originally was a TProc<T> . 它无法从TProc<T>参数推断T的原因是,那时TProc<TButton>是构造类型,没有任何信息表明它最初是TProc<T>

To do that it would have to infer the type from the anonymous method signature which does not work (I guess Barry Kelly could explain that better and I think he once wrote about the difficulties of lambdas and type inference in Delphi). 为此,必须从不起作用的匿名方法签名中推断类型(我想巴里·凯利(Barry Kelly)可以更好地解释这一点,我认为他曾经写过关于Lambda的难点和Delphi中的类型推断)。

The only type inference the Delphi compiler is capable of is an argument of type T. Even with multiple arguments that does not work often and even less if you have more than one generic type parameters. Delphi编译器唯一能够进行类型推断的是类型T的参数。即使有多个参数,它们通常不起作用,如果有多个泛型类型参数,甚至更少。

Edit: I found a comment where Barry explained a bit about the difficulties of type inference and lambdas in the Delphi compiler: http://www.deltics.co.nz/blog/posts/244/comment-page-1#comment-107 编辑:我找到了一条评论,其中Barry在Delphi编译器中解释了类型推断和lambda的困难: http : //www.deltics.co.nz/blog/posts/244/comment-page-1#comment- 107

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

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