有几个类,大部分属性基本一致,所以打算作一个基类,然后在这个基础上继承举个例子:TCustomItemSet = class(TPersistent)
public
......
property Item[Index Integer]: TCustomItemSet read GetItem write SetItem;
end;然后TItemSet定义如下TItemSet = class(TCustomItemSet);在使用过程中想如下使用:function GetItemSet(Index: Integer): TItemSet;
begin
with TItemSet.Create do
begin
Result := Item[Index];
end;
end;这个时候报编译错误:类型不一致。因为基类的Item属性返回的是TCustomItemSet,但我使用中要求返回TItemSet类型,
请问我该怎么作呢?
public
......
property Item[Index Integer]: TCustomItemSet read GetItem write SetItem;
end;然后TItemSet定义如下TItemSet = class(TCustomItemSet);在使用过程中想如下使用:function GetItemSet(Index: Integer): TItemSet;
begin
with TItemSet.Create do
begin
Result := Item[Index];
end;
end;这个时候报编译错误:类型不一致。因为基类的Item属性返回的是TCustomItemSet,但我使用中要求返回TItemSet类型,
请问我该怎么作呢?
//……你这儿Create的TItemSet在什么地方释放?
begin
Result := Item[Index] as TItemSet;
end;
要做的事情也不是很多。
begin
Item[Index] := TItemSet.Create;
Result := Item[Index];
end;还得保证数组Item是TItemSet类型with TItemSet.Create do 根本就没有意义呀
只要定义Item这个属性和相关方法即可。
begin
with TItemSet.Create do
begin
Result := TItemSet(Item[Index]);
end;
end;
调用的时候进行强制转换。
m:TItemSet;
m:=GetItemSet(3) as TItemSet;
Result := TItemSet(Item[Index]);但是VCL中一般是不采用这种方式的,而是返回一个通用的TCustomItemSet实例(TCustomItemSet的不同不同子类的Item属性返回不同的TCustomItemSet子类实例)。
如果要强制转化,你就必须保证TCustomItemSet.GetItem 返回的的确是TItemSet或者其子类的实例;通常可以将TCustomItemSet.GetItem 虚化,在TItemSet覆盖处理。
当然如果只是简单的:TItemSet = class(TCustomItemSet);
TItemSet 相对于TCustomItemSet没有添加任何的成员,那么才可以简单的强制转化,但是此时TItemSet就没有任何意义了。————————————————————————————————————
宠辱不惊,看庭前花开花落,去留无意;毁誉由人,望天上云卷云舒,聚散任风。
————————————————————————————————————
TCustomItemSet = class(TPersistent)
public
......
property Item[Index Integer]: TCustomItemSet read GetItem write SetItem;
--------------是这个吗, 不对吧
end;然后TItemSet定义如下TItemSet = class(TCustomItemSet);在使用过程中想如下使用:function GetItemSet(Index: Integer): TItemSet;
begin
with TItemSet.Create do
begin
Result := Item[Index];
end;
end;
使用一种语言,你必须遵守一些契约,这是难免的,你必须适应它,你想随心所欲,那是你熟悉它能做什么,不能做什么之后的事情。利用它能做的事情,绕过它不能做的,搭建出你想要得状态。