[英]How can a generic interface refer to a pointer to its type parameter?
In a nutshell, I want to be able to do something like this (where T is usually a record) 简而言之,我希望能够做到这样的事情(其中T通常是记录)
interface
ITable<T> = interface
...
other methods
...
function Append: ^T;
end;
But as we see in a question about declaring pointers based on generic types , Delphi doesn't allow the ^T
construction. 但正如我们在关于基于泛型类型声明指针的问题中所看到的,Delphi不允许
^T
构造。 If this were allowed, I could do stuff like: 如果这是允许的话,我可以做以下事情:
var
myrec: PMyRec;
myTable: ITable<TMyRec>;
begin
myTable := TableFactory.Build(TMyRec);
myRec := myTable.Append;
myRec.FieldA := 'Test';
.. Do stuff with myTable containing myRec
end;
The reason that I want to do this, is that I have a hell of a lot of existing code that is written that way around rather than building up a record then calling a procedure that accepts the built record like MyTable.Add(MyRec)
, which is the more Delphi-like way. 我想要这样做的原因是,我有很多现有的代码编写,而不是构建一个记录然后调用接受像
MyTable.Add(MyRec)
这样的构建记录的过程,这是更像Delphi的方式。
The solution to the linked question is to use an internal type
statement in the generic class, but generic interfaces don't allow type
statements. 链接问题的解决方案是在泛型类中使用内部
type
语句,但泛型接口不允许使用type
语句。
To get around this, I thought I may be able to use something like the Spring4D interfaced collections using a generic record to return the pointer as so: 为了解决这个问题,我想我可以使用类似Spring4D接口集合的东西使用泛型记录来返回指针,如下所示:
ListRec<T> = record
type
P = ^T;
private
InternalList = IList<T>;
public
... exposed list functions
function Append: PT;
end;
function ListRec<T>.Append: PT;
var
index: integer;
TempT: TMyRec;
begin
index := InternalList.add(TempT);
result := @InternalList.Items[index];
end;
After all that, my question is: Is there an easier way of achieving my objective or have I massively over-complicated it? 毕竟,我的问题是:是否有更简单的方法来实现我的目标或者我是否过度复杂化了它? Are there any obvious downsides (other than the standard risks of working with pointers)?
是否有任何明显的缺点(使用指针的标准风险除外)? I'd ideally prefer a pure interface solution for testability if nothing else.
理想情况下,如果没有别的,我更喜欢纯粹的接口解决方案。
In an ideal world, you would be able to declare a generic pointer type directly: 在理想的世界中,您可以直接声明泛型指针类型:
type
P<T> = ^T;
But the language does not permit this. 但语言不允许这样做。 You can declare generic pointer types but only if they are contained inside another type.
您可以声明泛型指针类型,但前提是它们包含在另一种类型中。 For instance:
例如:
type
PointerTo<T> = record
type
P = ^T;
end;
Now your interface can be: 现在您的界面可以是:
type
ITable<T> = interface
function Append: PointerTo<T>.P;
end;
Frankly, in my opinion, this is rather lame. 坦率地说,在我看来,这是相当蹩脚的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.