【问题标题】:how to change ItemClass of a class inherited from TCollection如何更改从 TCollection 继承的类的 ItemClass
【发布时间】:2012-07-10 20:29:25
【问题描述】:

我有一个从 TCollection 继承的类(我们称之为“TMyCollection”),我必须从它继承一个新类(我们称之为“TMyItems”)

通常我们在 TCollection 的构造函数中传递 ItemClass 类型,但在我的例子中,TMyCollection 的构造函数被新的构造函数覆盖,它不接受 ItemClass,它只接受 Owner。

如果继承的构造函数不接受 ItemClass 参数,我需要知道如何更改“TMyItems”中的 ItemClass。

问候。

【问题讨论】:

    标签: delphi tcollection tcollectionitem


    【解决方案1】:

    您仍然可以从子类中调用继承的 TCollection.Create,即使它没有相同的签名:

      TMyCollectionItem = class(TCollectionItem)
      private
        FIntProp: Integer;
        procedure SetIntProp(const Value: Integer);
      public
        property IntProp: Integer read FIntProp write SetIntProp;
      end;
    
      TMyCollection = class(TCollection)
      public
        constructor Create(AOwner: TComponent);virtual;
      end;
    
    { TMyCollection }
    
    constructor TMyCollection.Create(AOwner: TComponent);
    begin
      inherited Create(TMyCollectionItem); // call inherited constructor
    end;
    

    编辑

    根据原始发布者的 cmets,“技巧”是将新构造函数标记为重载。由于它是一个重载,它不会隐藏对 TCollection 构造函数的访问。

      TMyCollection = class(TCollection)
      public
        constructor Create(AOwner: TComponent);overload;  virtual;
      end;
    
      TMyItem = class(TCollectionItem)
      private
        FInt: Integer;
      public
        property Int: Integer read FInt;
      end;
    
      TMyItems = class(TMyCollection)
      public
        constructor Create(AOwner: TComponent);override;
      end;
    
    implementation
    
    { TMyCollection }
    
    constructor TMyCollection.Create(AOwner: TComponent);
    begin
      inherited Create(TCollectionItem);
    
    end;
    
    { TMyItems }
    
    constructor TMyItems.Create(AOwner: TComponent);
    begin
      inherited Create(TMyItem);
      inherited Create(AOwner); // odd, but valid
    end;
    
    end.
    

    【讨论】:

    • 问题是我有2级继承代码如下: TMyCollection = class(TCollection).... TMyCollection 的构造函数是构造函数 Create(AOwner: TComponent); TMyItems = class(TMyCollection) TMyItems 的构造函数:构造函数 Create(AOwner: TComponent);当尝试在 TMyItems 中调用继承的构造函数时,它将调用 TMyCollection 的构造函数,这不是我想要的,因为我有一个新的 ItemClass 并且它必须传递给集合...
    • 新的 ItemClass 也是从 TMyCollectionItem 继承的,因此它将具有 TMyCollectionItem 的所有属性和事件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 2019-09-04
    相关资源
    最近更新 更多