delphi - 用于定义泛型类正在实现的接口(interface)的泛型参数

标签 delphi delphi-xe4

是否可以使用通用参数来定义类正在实现的接口(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。我无法修改 TBarBaseTMyWrapperTFooComp(一种适配器模式)的包装器。

每个 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/

相关文章:

delphi - Firemonkey 样式设计器中另一个列表框中的列表框

delphi - Firemonkey designide.dcp 64 位

delphi - 使用 SSE2 在 Delphi 中内联汇编低效程序

delphi - 为什么 Delphi Prism 提示系统类型不匹配?

delphi - INDY - 我真的需要 cookies 吗?

delphi - 意外插入空格 - 为什么会编译?

delphi - TPopupMenu 项目未显示加速字符,是 Windows 设置问题还是什么?

delphi - 检测字符串是否包含 float ?

delphi - Delphi 决策支持组件发生了什么变化?

delphi - 为什么Delphi编译器不内联汇编函数?