2

可能重复:
通用方法在 Delphi 2010 中返回通用接口

在 Delphi 2010 中,什么时候可以ISomeGenericInterface<T>分配给ISomeGenericInterface<T>?

以下程序按预期编译和运行...

unit uGenDemo;
interface

{.$define declare-a-type}

function Tokenize: IEnumerator<string>;
{$IFDEF declare-a-type}
type TX = integer;
{$ENDIF}

implementation  

uses SysUtils;

type
IStringEnumerator = interface( IEnumerator<string>)
    ['{3A28E4FB-CDF7-4933-8D67-D9EF5C2466E0}']
  end;

TBaseEnumerator = class( TInterfacedObject, IEnumerator)
  private
    function  MoveNext: Boolean;
    function  BaseGetCurrent: TObject;
    function  IEnumerator.GetCurrent = BaseGetCurrent;
    procedure Reset;
  end;

TStringEnumerator = class( TBaseEnumerator, IStringEnumerator)
  private
    function GetCurrent: string;
    property Current: string read GetCurrent;
  end;

function Tokenize: IEnumerator<string>;
begin
result := TStringEnumerator.Create as IStringEnumerator
end;


{ TBaseEnumerator }

function TBaseEnumerator.BaseGetCurrent: TObject;
begin
result := nil
end;

function TBaseEnumerator.MoveNext: Boolean;
begin
result := False
end;

procedure TBaseEnumerator.Reset;
begin
end;

{ TStringEnumerator }

function TStringEnumerator.GetCurrent: string;
begin
result := ''
end;


end.

...但是,当我们在声明函数后声明任何类型时Tokenize(),例如,通过将行从 ...

{.$define declare-a-type}

... 至 ...

{$define declare-a-type}

...编译器阻止并抛出错误...

[DCC Error] uGenDemo.pas(43): E2010 Incompatible types: 'IEnumerator<System.string>' and 'IStringEnumerator'

为什么?

  1. 这是编译器错误吗?
  2. 一般来说,将接口指针分配给一般参数化的祖先类型的接口指针是否安全?

(我的编译器版本是 Embarcadero® Delphi® 2010 Version 14.0.3593.25826)

4

0 回答 0