简体   繁体   English

Delphi 2010-为什么我不能声明带有泛型类型参数的抽象方法?

[英]Delphi 2010 - Why can't I declare an abstract method with a generic type parameter?

I am trying to do the following in Delphi 2010: 我正在尝试在Delphi 2010中执行以下操作:

TDataConverter = class abstract
public
    function Convert<T>(const AData: T): string; virtual; abstract;
end;

However, I keep getting the following compiler error: 但是,我不断收到以下编译器错误:

E2533 Virtual, dynamic and message methods cannot have type parameters

I don't quite understand the reason why I can't do this. 我不太明白为什么我不能这样做。 I can do this in C# eg 我可以在C#中做到这一点

public abstract class DataConverter
{
    public abstract string Convert<T>(T data);
}

Anyone know the reasoning behind this? 有人知道这背后的原因吗?

You can do it in .NET because Delphi and .NET handle generics differently. 您可以在.NET中完成此操作,因为Delphi和.NET对泛型的处理方式不同。 I don't know enough to go into detail. 我还不了解细节。 I do know why you can't do it in Delphi, though. 我确实知道为什么您不能在Delphi中做到这一点。

Every virtual method has to have a slot in the virtual method table for the class. 每个虚拟方法都必须在该类的虚拟方法表中具有一个插槽。 This has to be set up when the unit is compiled so its information can be put into the DCU. 必须在编译单元时进行设置,以便其信息可以放入DCU中。 (And likewise, every dynamic method has to have an entry in the dynamic method table, at the time when the unit is compiled.) (同样,在编译单元时,每个动态方法都必须在动态方法表中有一个条目。)

But if you create generic methods, each time you invoke it in code, a different copy of the code gets created, specific to that type parameter. 但是,如果创建泛型方法,则每次在代码中调用它时,都会创建该类型参数专用的不同代码副本。 This is necessary for handling different types in different ways. 这对于以不同方式处理不同类型是必需的。 (If you pass in an interface or a string, for example, it has to take care of the reference count.) But you can't create new virtual methods and new VMT slots for them, since the DCU has already been created and can't be changed now . (例如,如果传入接口或字符串,则它必须处理引用计数。)但是您无法为其创建新的虚拟方法和新的VMT插槽,因为DCU已经创建并且可以现在不被更改

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

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