【问题标题】:Delphi: properties with same name in descending classDelphi:降序类中具有相同名称的属性
【发布时间】:2009-03-18 17:05:38
【问题描述】:

在一个文件中,我有一个带有 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 字段?

【问题讨论】:

    标签: delphi inheritance properties


    【解决方案1】:

    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;
    

    【讨论】:

    • 请不要使用“覆盖”来描述这一点。这表明有些东西与虚函数和多态性有关,但没有。 TList 类型的变量将始终访问 TList 的 Items 属性,即使该变量包含 TMyList 类的实例。一个更好的词是“隐藏”。
    • Reintroduce 是一个更好的词。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多