这个问题已经被问了很多次,但我还没有找到答案。
请有人为我澄清一些事情。 使用:Delphi XE2
我有一个非常大的BaseObject,几乎用于所有事情。 除此之外,我还有一个通用列表 - BaseList。
声明如下:
TBaseObject = class
... a lot of properties and methods ...
end;
TBaseList<T: TBaseObject> = class(TObjectList<T>)
... some properties and methods ...
end;
我最近尝试将非常老旧的TStringList声明中使用的Objects[]属性更改为更加通用的泛型列表TObjectList。
但我遇到了一些问题。 BaseUnit是一个文件...每次我派生我的BaseObject时,我也会制作一个专门的列表来跟随它。
所以我会像这样做:
TCustomer = class(TBaseObject)
... customer related stuff ...
end;
TCustomerList<T: TCustomer> = class(TBaseList<T>)
... customer list specific stuff ...
end;
但现在我希望有一个对象来包含一个列表——可以容纳任何对象。我想我可以这样做:
TControlObject = class(TBaseobject)
FGenList: TBaseList<TBaseObject>;
end;
由于BaseList和BaseObject是我的继承结构的顶端,我认为这样的列表可以容纳任何我能想到的列表。
但我觉得我在这里失败了... 一个TBaseList<TBaseobject>与TCustomerList<TCustomer>不可比较... 即使TCustomerList和TCustomer都是从我的基类派生而来。
我希望能够在baselist中使用泛型来实例化新对象。 例如,在populate方法中使用T.Create。
以下是完整继承结构的示例:
Base Unit;
TBaseObject = class
end;
TBaseList<T:TBaseObject> = class(TObjectList<T>)
end;
CustomCustomer Unit;
TCustomCustomer = class(TBaseObject)
end;
TCustomCustomerList<T:TCustomCustomer> = class(TBaseList<T>)
end;
Customer Unit;
TCustomer = class(TCustomCustomer)
end;
TCustomerList<T:TCustomer> = class(TCustomCustomerList<T>)
end;
CustomPerson Unit;
TCustomPerson = class(TBaseObject)
end;
TCustomPersonList<T:TCustomPerson> = class(TBaseList<T>)
end;
Person Unit;
TPerson = class(TCustomPerson)
end;
TPersonList<T:TPerson> = class(TCustomPersonList<T>)
end;
考虑到上述的层次结构,为什么我不能:
var
aList : TBaseList<TBaseObject>; // used as a list parameter for methods
aPersonList : TPersonList<TPerson>;
aCustomerList : TCustomerList<TCustomer>;
begin
aPersonList := TPersonList<TPerson>.Create;
aCustomerList := TCustomerList<TCustomer>.Create;
aList := aCustomerList; <-- this FAILS !! types not equal ..
end;
调用处理所有列表基类的过程会以相同方式失败...
Procedure LogStuff(SomeList : TBaseList<TBaseObject>)
begin
writeln(Format( 'No. Elements in list : %d',[SomeList.Count]));
end;
有人能打我一拳并告诉我这里出了什么问题吗?
FList := TBaseList<TPerson>.Create
是不可能的 - 因为 FList 属于另一种类型TBaseList<TBaseObject>
。 - Bimmer_R