delphi - 这个不兼容的类型错误怎么了

标签 delphi

我几天去了,有人问我为什么这段代码给出了错误。我试图弄清楚,但我不能,所以我希望你们能帮助我们。

第一个单元:定义类的位置
单位Unit1;

interface

type
  TSomeGeneric<T> = class
  private
    function getSelf: TSomeGeneric<T>;
  public
    property This : TSomeGeneric<T> read getSelf;
  end;

implementation

{ TSomeGeneric<T> }

function TSomeGeneric<T>.getSelf: TSomeGeneric<T>;
begin
  Result := Self;
end;

end.


unit2:它引用在单元1中定义的类
单位Unit2;

interface

uses
  Unit1;

type
  TSomeGeneric<T> = class(Unit1.TSomeGeneric<T>);

implementation

end.


frmmain:它使用unit2是一点
单位ufrmMain;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,

  Unit2;

type
  TfrmMain = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    procedure SomeProcedure(ASG : TSomeGeneric<Integer>);
  public
    { Public declarations }
  end;

var
  frmMain: TfrmMain;

implementation

{$R *.dfm}

{ TfrmMain }

procedure TfrmMain.FormCreate(Sender: TObject);
var ASG : TSomeGeneric<Integer>;
begin
  ASG := TSomeGeneric<Integer>.Create();
  with ASG do
    try
      //make use os the class ...
      SomeProcedure(This); //error -> incompatible types
    finally
      Free();
    end;
end;

procedure TfrmMain.SomeProcedure(ASG: TSomeGeneric<Integer>);
begin
  //...
end;

end.


我有点怀疑,此时TSomeGeneric = class(Unit1.TSomeGeneric)TSomeGeneric被定义为另一个类,而不是引用,但是我无法确认

最佳答案

编译器很清楚。有问题的行是这一行:

  SomeProcedure(This);


错误是:

[dcc32 Error] E2010 Incompatible types: 'Unit2.TSomeGeneric' and 
'Unit1.TSomeGeneric'

That's because in that method call:

  • This is of type Unit1.TSomeGeneric<System.Integer> and
  • SomeProcedure expects a parameter of type Unit2.TSomeGeneric<System.Integer>.

And those are not the same type because you explicitly made them different.

type
  TSomeGeneric<T> = class(Unit1.TSomeGeneric<T>);


定义了一个新类型,现在您有两种不兼容的类型。

您只需要删除Unit2。除了停止合理的代码编译外,它没有其他目的。

关于delphi - 这个不兼容的类型错误怎么了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17115400/

相关文章:

delphi - 我将如何测试日期是否在日期范围内(两个字符串)?

delphi - 将项目加载到 Delphi XE6 时出现随机错误

delphi - 比较字符串的一部分

wcf - Delphi 客户端使用的 WCF 中生成的 WSDL

json - 如何检查 SuperObject 中是否存在特定元素?

windows - 通过 WinAPI 和 Delphi 在 Skype 客户端中查找和使用当前事件的聊天框?

德尔福+突触: How to check the size of the response with TTCPBlockSocket

android - Android 和 iOS 上的 ipv6 和 TidHTTP 问题

delphi - 通过集合/列表/其他容器使用 AWE Memory 进行数据存储

delphi - Delphi的BeginThread阻塞函数