无法转换TList <t>项作为接口

时间:2015-10-01 23:52:18

标签: delphi generics interface delphi-xe7

为什么此代码无法从需要特定接口的泛型列表转换为IDeletableNode。

无论我如何投射,此代码示例都无法执行IDeletableNode.Delete过程。

    unit DeletableGenericsTest;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, xmldom, XMLDoc, XMLIntf, Generics.Collections;

type

  IDeletableNode = interface(IXMLNode)
    ['{04D7A0C0-8E87-412B-BC55-230C7080D410}']
    procedure Delete;
  end;

  INodeOfData = interface(IDeletableNode)
     ['{368917D8-402F-4BA2-8BC5-B0DB51B1BAE9}']
     function Get_MyKey : string;
     property MyKey : string read Get_MyKey;
  end;

  TDeletableList<T: IDeletableNode> = class(TList<T>)
     procedure DeleteAll;
  end;

  TNodeOfData = class(TXMLNode, INodeOfData)
  protected
     function Get_MyKey: string;
  public
     procedure Delete;
  end;

  TForm1 = class(TForm)
  private
    fListOfNodes : TDeletableList<TNodeOfData>;
  public
    { Public declarations }
  end;


var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TDeletableList<T> }

procedure TDeletableList<T>.DeleteAll;
var
index : Integer;
begin
   for index := Self.Count - 1 downto 0 do
       Self[index].Delete;
end;

{ TNodeOfData }

procedure TNodeOfData.Delete;
begin
   // delete some stuff;
end;

function TNodeOfData.Get_MyKey: string;
begin
   result := '123ABC';
end;

end.

我在这里缺少什么或者这是正确的吗?

1 个答案:

答案 0 :(得分:2)

您问题中的代码因此错误而失败:

  

[dcc32错误] E2514类型参数&#39; T&#39;必须支持界面&#39; IDeletableNode&#39;

在这一行:

fListOfNodes : TDeletableList<TNodeOfData>;

编译器非常清楚地告诉你,TNodeOfData必须实现IDeletableNode,而不是TDeletableList<T: IDeletableNode> = class(TList<T>) 。这是因为对泛型参数的约束:

TNodeOfData = class(TXMLNode, INodeOfData)

所以改变

TNodeOfData = class(TXMLNode, IDeletableNode, INodeOfData)

my_func

您的代码将被编译。