泛型,接口和继承问题

RjK*_*RjK 6 delphi generics interface

以下示例给出了此错误:
[DCC Error] Unit2.pas(54): E2010 Incompatible types: 'IBar' and 'Unit2.TFoo<Unit2.IBar>'

我认为问题出在Self.Create周围因为经过多次尝试编译后我不小心输入了FFoo:= TBar(Self).Create; 它编译和工作.

我正在使用Delphi XE

IFoo = interface
end;

TFoo<T: IInterface> = class(TInterfacedObject, IFoo)
private class var
  FFoo: T;
public class
  function Instance: T;
end;

IBar = interface(IFoo)
end;

TBar = class(TFoo<IBar>, IBar)
end;

class function TFoo<T>.Instance: T;
begin
  if not Assigned(FFoo) then
  begin
    FFoo := Self.Create;
  end;
  Result := FFoo;
end;
Run Code Online (Sandbox Code Playgroud)

Ste*_*nke 1

您的 TFoo 没有将 T 实现为接口。这就是 FFoo 和 TFoo 实例不兼容的原因。如果要将 TFoo 的实例分配给 FFoo,则需要对其进行硬强制转换。