我正在尝试编写一个基本的工厂方法来返回一个通用接口类。
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;
它看起来很简单,我相信我以前也写过类似的代码,但当我尝试编译时,我得到了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;
或者在另一类中:
type
TBuilder<T> = class
private
type
TInterfaceImpl = class(TInterfacedObject, IGenInterface<T>)
public
function TestGet: T;
end;
public
class function Build: IGenInterface<T>;
end;