【问题标题】:Problem with generics and interfaces and inheritance泛型、接口和继承的问题
【发布时间】:2011-06-14 04:43:59
【问题描述】:

下面的例子给了我这个错误:
[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;

【问题讨论】:

  • 错误告诉你一个行号。也许您可以准确指出那是哪一行,而不是猜测问题可能出在哪里?
  • 错误就在“end”之后的那一行
  • 演员 TBar(Self).Create 是不需要的,因为您不确定 Self 是 TBar 并且它将打破泛型的概念(不能用于其他类)!跨度>
  • 这里不支持行号真的很可惜。
  • 2017 和 Tokyo.2 还是一样

标签: delphi generics interface


【解决方案1】:

问题出在 TBar 声明的这一行:

FFoo := Self.Create;

为了理解,让我们解释一下代码背后的类型[注释如下]:

FFoo:[IBar] := Self:[TFoo(IBar)].Create():[TFoo<IBar>]

所以,你总结一下,我们有:[IBar] := [TFoo&lt;IBar&gt;]
这些类型兼容吗?
[TFoo] 只实现 IFoo 接口,没有 IBar 如您的代码中所述

TFoo<T: IInterface> = class(TInterfacedObject, IFoo)

这是编译错误!
更新:解决方案 1
要解决此问题:更改 TBar 声明

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

更新:解决方案 2
FFoo := Self.Create 替换为

FFoo := Self.Create.Instance;

所以它起作用了!

【讨论】:

  • 这不是解决方案,因为函数 Instance 的结果类型将是 IFoo 而不是 IBar。
  • @RjK:我已经用 Solution 2 更新了我的帖子。我想这就是搜索的内容!
  • 更新:解决方案 2 -> 这将导致堆栈溢出。
【解决方案2】:

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

【讨论】:

  • 你的意思是函数实例中的这个:结果:= T(FFoo);它可以编译,但是当我运行它时,我在函数的最后一端得到一个 AV。 (地址 00000001 的访问冲突。读取地址 00000001。)
猜你喜欢
  • 2012-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 2011-08-01
相关资源
最近更新 更多