问一个类的写法 ( 积分: 20 )

  • 主题发起人 主题发起人 loskiller
  • 开始时间 开始时间
L

loskiller

Unregistered / Unconfirmed
GUEST, unregistred user!
Ta=class
end;

Tb=class(Ta)
end;

Taa=class
.......
property Item[inedx:integer]:Ta......;default

end

Tbb=class(Taa)
.......
//property Item[inedx:integer]:Tb......;default

end;

var
aa:Taa;
bb:Tbb;

当我访问aa[0]时,类型Ta,访问bb[0]时类型也是Ta。
现在我想访问bb[0]是,类型直接是Tb,而不用加强制转换。我也不想重新写一遍GetItem这些方法。
 
在getItem 中做手脚,设成虚函数
 
我就是不想重写getitem方法啊
 
楼上的,参考一下TCollection和TCollectionItem的写发。类似的代码很容易写的。我帖一段你看看:
TCustomElementItem = class(TCollectionItem)
private
FChecked: Boolean;
FTagId: Integer;
FTagIndex: Integer;
...
published
property Checked: Boolean read FChecked write SetChecked;
property TagId: Integer read GetTagId write SetTagId;
property TagIndex: Integer read GetTagIndex write SetTagIndex;
end;

TCustomElements = class(TOwnedCollection)
private
function GetItem(Index: Integer): TCustomElementItem;
procedure SetItem(Index: Integer
const Value: TCustomElementItem);
protected
procedure NotifyChange;
public
function Add(AComponent: TCustomTemplateComponent): TCustomElementItem;
property Items[Index: Integer]: TCustomElementItem read GetItem write SetItem
default;
end;

TImageElementItem = class(TCustomElementItem)
private
FNewImageFilePath: string;
procedure SetNewImageFilePath(const Value: string);
published
function GetAllowFileExtention: string;
property NewImageFilePath: string read FNewImageFilePath
write SetNewImageFilePath;
end;

TImageElements = class(TCustomElements)
private
function GetItem(Index: Integer): TImageElementItem;
procedure SetItem(Index: Integer
const Value: TImageElementItem);
public
constructor Create(AOwner: TPersistent)
reintroduce;
function Add(AComponent: TImgTemplateComponent): TImageElementItem;
property Items[Index: Integer]: TImageElementItem read GetItem write SetItem
default;
end;



{ TCustomElements }

function TCustomElements.Add(AComponent: TCustomTemplateComponent):
TCustomElementItem;
begin
Result := TCustomElementItem(inherited Add);
...
Result.TagId := AComponent.TagId;
Result.TagIndex := AComponent.TagIndex;
...
end;

function TCustomElements.GetItem(Index: Integer): TCustomElementItem;
begin
Result := TCustomElementItem(inherited GetItem(index));
end;

procedure TCustomElements.SetItem(Index: Integer;
const Value: TCustomElementItem);
begin
inherited SetItem(Index, Value);
end;

{ TImageElements }

constructor TImageElements.Create(AOwner: TPersistent);
begin
inherited Create(AOwner, TImageElementItem);
end;

function TImageElements.Add(AComponent: TImgTemplateComponent):
TImageElementItem;
begin
Result := TImageElementItem(inherited Add(AComponent));
end;

function TImageElements.GetItem(Index: Integer): TImageElementItem;
begin
Result := TImageElementItem(inherited GetItem(Index));
end;

procedure TImageElements.SetItem(Index: Integer;
const Value: TImageElementItem);
begin
inherited SetItem(Index, Value);
end;
 
多人接受答案了。
 
后退
顶部