我想创建一个通用列表类与tiOPF(delphi @ www.tiopf.com的对象持久化框架)一起使用。具体来说,我正在尝试使用现有的泛型类(TtiObjectList)并制作一个使用TtiObject降级的泛型版本。德尔菲通用约束问题
由于需要在D7 - D2009和Free Pascal下编译,所以我修改基类的范围有限。我需要从TtiObjectList下降以保持现有的持久性机制正常工作。
// base class
type
TtiObjectList = class(TtiObject)
...
protected
function GetItems(i: integer): TtiObject; virtual;
procedure SetItems(i: integer; const AValue: TtiObject); virtual;
...
public
function Add(const AObject : TtiObject): integer; overload; virtual;
...
end;
我的类定义如下:
TtiGenericObjectList<T: TtiObject> = class(TtiObjectList)
protected
function GetItems(i:integer): T; reintroduce;
procedure SetItems(i:integer; const Value: T); reintroduce;
public
function Add(const AObject: T): integer; reintroduce;
property Items[i:integer]: T read GetItems write SetItems; default;
end;
implementation
{ TtiGenericObjectList<T> }
function TtiGenericObjectList<T>.Add(const AObject: T): integer;
var obj: TtiObject;
begin
obj:= TtiObject(AObject); /// Invalid typecast
result:= inherited Add(obj);
end;
// alternate add, also fails
function TtiGenericObjectList<T>.Add(const AObject: T): integer;
begin
result:= inherited Add(AObject); /// **There is no overloaded version**
/// **of 'Add' that can be called with these arguments**
end;
function TtiGenericObjectList<T>.GetItems(i: integer): T;
begin
result:= T(inherited GetItems(i)); /// **Invalid typecast **
end;
procedure TtiGenericObjectList<T>.SetItems(i: integer; const Value: T);
begin
inherited SetItems(i, Value);
end;
我的问题是,德尔福没有看到T作为一个TtiObject后代。我收到无效的类型转换错误,当我做这样的事情:
function TtiGenericObjectList<T>.Add(const AObject: T): integer;
var obj: TtiObject;
begin
obj:= TtiObject(AObject); /// **Invalid typecast***
result:= inherited Add(obj);
end;
如果我不这样做类型转换,然后我得到过载的错误,而不是在上面的列表中显示。
任何想法我错了吗?
肖恩
这是Delphi 2009编译器中的一个错误;我认为这是在Delphi 2010编译器中解决的。 – 2009-10-27 11:05:14