为什么此代码无法从需要该特定接口的泛型列表中强制转换为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.


我在这里缺少什么还是正确的?

最佳答案

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


[dcc32错误] E2514类型参数“ T”必须支持接口“ IDeletableNode”


在这一行:

fListOfNodes : TDeletableList<TNodeOfData>;


编译器已经非常清楚地告诉您,TNodeOfData必须实现IDeletableNode,而没有。之所以这样是因为对通用参数的约束:

TDeletableList<T: IDeletableNode> = class(TList<T>)


所以改变

TNodeOfData = class(TXMLNode, INodeOfData)




TNodeOfData = class(TXMLNode, IDeletableNode, INodeOfData)


然后您的代码将被编译。

关于delphi - 无法转换为接口(interface)的TList <T>项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32898540/

10-12 14:44