【问题标题】:Descending generic TObjectLIst降序通用 TObjectLIst
【发布时间】:2012-10-29 10:27:36
【问题描述】:

假设我有一个基类:

  TPart = class
  private   
    FPartId: Integer;
  public
    property PartId: Integer read FPartId write FPartId;
  end;

我有一个通用列表:

  TPartList = class(TObjectList<TPart>)
  public
    function IndexOfPart(PartId: Integer): Integer;
  end;

现在,如果我从我的 TPart 下降:

  TModulePart = class(TPart)
  private
    FQuantity: Integer;
  public
    property Quantity: Integer read FQuantity write FQuantity;
  end;

我现在想创建一个 TPartList 的后代,但能够返回一个 TModulePart 项。这样做:

  TModulePartList = class(TPartList)
  end;

默认情况下会认为 Items 属性的类型是 TPart 而不是 TModulePart (自然)。我不想这样做:

  TModulePartList = class(TObjectList<TModulePart>)
  end;

因为我错过了从 TPartList 中可能拥有的常用方法的继承。

有可能吗?

谢谢

【问题讨论】:

    标签: delphi generics delphi-xe2


    【解决方案1】:

    你可以像这样做你想做的事:

    TGenericPartList<T: TPart> = class(TObjectList<T>)
    public
      function IndexOfPart(PartId: Integer): Integer;
    end;
    TPartList = TGenericPartList<TPart>;
    TModulePartList = TGenericPartList<TModule>;
    

    如果你像这样设计它,你可以增加更多的灵活性:

    TGenericPartList<T: TPart> = class(TObjectList<T>)
    public
      function IndexOfPart(PartId: Integer): Integer;
    end;
    TPartList = TGenericPartList<TPart>;
    
    TGenericModulePartList<T: TModule> = class(TGenericPartList<T>)
      procedure DoSomething(Module: T);
    end;
    TModulePartList = TGenericModulePartList<TModule>;
    

    【讨论】:

      猜你喜欢
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 2017-12-24
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多