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;
答案 0 :(得分:1)
As the documentation states:Items
的属性Contnrs.TObjectList
的类型为TObject
:
property Items[Index: Integer]: TObject read GetItem write SetItem; default;
另一方面,类型参数T
不受约束,可以是任何类型,例如Integer
之类的值类型。
如果添加generic type constraint,代码应编译:
TObjectListEnumerator<T: TObject> = class