DelphiXE3和无效的通用类型转换

时间:2013-06-19 06:40:30

标签: delphi generics casting delphi-xe3

Delphi2010编译我的TObjectListEnumerator类没有错误, 但是DelphiXE3给出了编译器错误:E2089:无效的类型转换

这有什么问题?

    TObjectListEnumerator<T> = class
      private
        fList     : TObjectList;
        fIndex    : integer;
        fMaxIndex : integer;
        function GetCurrent : T;
      public
        constructor Create(List: TObjectList);
        function MoveNext : Boolean;
        property Current  : T read GetCurrent;
      end;

    constructor TObjectListEnumerator<T>.Create(List: TObjectList);
    begin
      inherited Create;
      fList     := List;
      fIndex    := -1;
      fMaxIndex := fList.Count-1;
    end;

    function TObjectListEnumerator<T>.MoveNext: Boolean;
    begin
      Inc(fIndex);
      Result := not(fIndex > fMaxIndex);
    end;

    function TObjectListEnumerator<T>.GetCurrent: T;
    begin
      Result := T(fList[fIndex]);  // <-- E2089: Invalid typecast 
    end;

1 个答案:

答案 0 :(得分:1)

As the documentation statesItems的属性Contnrs.TObjectList的类型为TObject

property Items[Index: Integer]: TObject read GetItem write SetItem; default;

另一方面,类型参数T不受约束,可以是任何类型,例如Integer之类的值类型。

如果添加generic type constraint,代码应编译:

TObjectListEnumerator<T: TObject> = class