开发者

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

I am trying to do the follow开发者_StackOverflow社区ing in 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# e.g.

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. I don't know enough to go into detail. I do know why you can't do it in Delphi, though.

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. (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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜