Mat*_*ood 2 delphi generics interface delphi-xe2
我正在尝试编写一个基本的工厂方法来返回一个通用的接口类.
interface
type
IGenInterface<T> = interface
function TestGet:T;
end;
TBuilder<T> = class
class function Build: IGenInterface<T>;
end;
TBuilder = class
class function Build<T>: IGenInterface<T>;
end;
implementation
type
TInterfaceImpl<T> = class(TInterfacedObject, IGenInterface<T>)
function TestGet:T;
end;
{ TBuilder }
class function TBuilder.Build<T>: IGenInterface<T>;
begin
result := TInterfaceImpl<T>.create;
end;
{ TInterfaceImpl<T> }
function TInterfaceImpl<T>.TestGet: T;
begin
end;
Run Code Online (Sandbox Code Playgroud)
它看起来很简单,我确信我之前已经编写过相似的代码,但是一旦我尝试编译,我就会得到E2506:接口部分声明的参数化类型的方法不能使用本地符号'.TInterfaceImpl` 1'.TBuilder的味道都不起作用,都失败了同样的错误.
现在,我不知道在哪里.,并1从都来了.在我的"真实"代码中,.它不存在,但是`1是.
我已经看过引用这个错误的另外两个SO问题了,但是我没有使用任何常量或分配变量(函数返回除外),也没有任何类变量.
有没有人有办法做到这一点,而无需将大量代码移动到我的界面?
该问题涉及泛型的实现细节.当您在不同单元中实例化泛型类型时,需要查看该TInterfaceImpl<T>单元中的类型.但编译器无法看到它,因为它位于不同单元的实现部分中.正如您所观察到的那样编译器对象.
最简单的解决方法是移动TInterfaceImpl<T>到在接口部分中声明的类型之一中声明的私有类型.
type
TBuilder = class
private
type
TInterfaceImpl<T> = class(TInterfacedObject, IGenInterface<T>)
public
function TestGet: T;
end;
public
class function Build<T>: IGenInterface<T>;
end;
Run Code Online (Sandbox Code Playgroud)
或者在其他类中:
type
TBuilder<T> = class
private
type
TInterfaceImpl = class(TInterfacedObject, IGenInterface<T>)
public
function TestGet: T;
end;
public
class function Build: IGenInterface<T>;
end;
Run Code Online (Sandbox Code Playgroud)