morrisseyd
morrisseyd

Reputation: 196

Not able to cast TList<T> item that is an interface

Why is it that this code can not cast to IDeletableNode from a generics list that requires that specific interface.

This code sample can not execute the IDeletableNode.Delete procedure no matter how I cast it.

    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.

Is there something that I am missing here or is this correct?

Upvotes: 1

Views: 156

Answers (1)

David Heffernan
David Heffernan

Reputation: 613461

The code in your question fails with this error:

[dcc32 Error] E2514 Type parameter 'T' must support interface 'IDeletableNode'

at this line:

fListOfNodes : TDeletableList<TNodeOfData>;

The compiler has told you, quite clearly, that TNodeOfData must implement IDeletableNode, which it does not. This is so because of the constraint on the generic parameter:

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

So change

TNodeOfData = class(TXMLNode, INodeOfData)

to

TNodeOfData = class(TXMLNode, IDeletableNode, INodeOfData)

and your code will compile.

Upvotes: 2

Related Questions