在一个文件中,我有一个带有ID属性的基类:
type
TBase = class(TObject)
private
FID: integer;
public
property ID: integer read FID write SetID;
end;
在第二个文件中,我有另一个类,从TBase下降。无论是偶然的,还是无知的,都是一个与现有财产/领域同名的新财产/领域。
type
TSub = class(TBase)
private
FID: Longword;
public
property ID: Longword read FID write FID;
end;
第二个ID字段当然是重命名的,但为什么编译器允许这样做?
在代码中访问ID时 - 使用哪个ID字段?
答案 0 :(得分:11)
Delphi允许它“隐藏”您的旧属性并引入具有不同操作的相同名称的属性。我已经用它来为特定的类或记录创建我自己的类型安全TList后代:
type
TMyList = class(TList)
private
function GetItem(Index: Integer): TMyObject;
procedure SetItem(Index: Integer; Value: TMyObject);
public
property Items[Index: Integer]: TMyObject read GetItem write SetItem;
end;
function TMyList.GetItem(Index: Integer): TMyObject;
begin
Result := TMyObject(inherited Items[Index]);
end;
procedure SetItem(Index: Integer; Value: TMyObject);
begin
inherited Items[Index] := Value;
end;
当然,使用Delphi 2009和泛型,它现在变得容易多了。
您要访问的ID取决于您从中呼叫ID的位置。
procedure TSub.Foo;
begin
ID := 5; //TSub.ID
inherited ID := 6 //TBase.ID
end;
procedure TBase.FooBar;
begin
ID := 5; //TBase.ID
end;
var
Sub: TSub;
Base: TBase;
begin
Sub := TSub.Create;
try
Sub.ID := 1; //assign 1 to TSub.ID
TBase(Sub).ID := 2; //assign 2 to TBase.ID
WriteLn(Sub.ID); //writes 1
WriteLn(TBase(Sub).ID); //writes 2
Base := Sub;
WriteLn(Base.ID); //writes 2
finally
Sub.Free;
end;
end;