是否可以使用通用参数来定义类正在实现的接口(interface)?
或者有人有解释,为什么 Delphi 不允许这样做(或者我只是做错了?):
TInterfacedMyWrapper<T: IInterface> = class(TMyWrapper, T)
function PropGetIntf(): T;
property Intf: T read PropGetIntf implements T;
end;
这会产生以下错误:
E2205:需要接口(interface)类型
E2259:Implements 子句仅允许用于类或接口(interface)类型的属性
这是我的解决方法:
TInterfacedMyWrapper<T: IInterface> = class(TMyWrapper)
function PropGetIntf(): T;
property Intf: T read PropGetIntf;
end;
TIFooMyWrapper = class(TInterfacedMyWrapper<IFoo>, IFoo)
property Intf: IFoo read PropGetIntf implements IFoo;
end;
但这迫使我为每个接口(interface)定义一个单独的类。我宁愿写:
TInterfacedMyWrapper<IFoo>.Create(CompToWrap);
已编辑(更多上下文来解释我的目标 - 我希望它不会太困惑......):
我有多个派生自 TFooComp
的类,这些类无法修改。我有一个包装类TMyWrapper
,它继承自TBarBase
。我无法修改 TBarBase
。
TMyWrapper
是 TFooComp
(一种适配器模式)的包装器。
每个 TFooComp
派生类都可以公开一个接口(interface)。我想要达到的是, TInterfacedMyWrapper
也公开了该接口(interface)(并将其委托(delegate)给
包装TFooComp
)。
这在某种程度上起作用:
constructor TMyWrapper.CreateNew(AOwner: TComponent; FooClass: TFooClass);
begin
FWrappedFooComp := FooClass.Create(Self);
//...
end;
//...
function TInterfacedMyWrapper<T>.PropGetIntf(): T;
begin
//see http://stackoverflow.com/questions/4418278/use-of-supports-function-with-generic-interface-type
if not Supports(FWrappedFooComp, GetTypeData(TypeInfo(T))^.Guid, Result) then
raise Exception.Create('Interface not implemented');
end;
但是对于每个 TFooComp
派生类,我必须创建一个自己的包装类(只有一个声明):
TWrappedFooXxx = class(TInterfacedMyWrapper<IXxx>, Ixxx)
property Intf: IXxx read PropGetIntf implements IXxx;
end;
我可以使用以下方式:
Result := TWrappedFooXxx.CreateNew(Owner, TFooXxx);
Result.DoSomething();
(Result as IXxx).DoSomeMore();
创建自己的包装类的必要性是我试图避免的。我宁愿只写:
Result := TInterfacedMyWrapper<IXxx>.CreateNew(Owner, TFooXxx);
Result.DoSomething();
(Result as IXxx).DoSomeMore();
最佳答案
why Delphi does not allow this?
因为这不是 C++ 模板。 Delphi 中的编译器需要知道您的类正在实现的接口(interface)(尽管它是通用的)。但在这种情况下不能,因为您正在尝试实现一个未知的接口(interface)。
关于delphi - 用于定义泛型类正在实现的接口(interface)的泛型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37408689/