【问题标题】:Pass a class with Generic parameter to another class in Delphi将具有通用参数的类传递给 Delphi 中的另一个类
【发布时间】:2015-07-25 08:04:07
【问题描述】:

我在 Delphi XE5 中有 2 个课程,并将一个传递给另一个:

  TfrmBaseList = class(TForm)
  private
    FListOwner: TSystemBaseList<TSystemColumnEntity>;
  public
    constructor Create(AListOwner: TSystemBaseList<TSystemColumnEntity>); virtual;
  end

  TSystemBaseList<T: TSystemColumnEntity> = class(TPersistent)
  public
    procedure Execute;
    property SelectedValues: TObjectList<T> read 
  end;


  procedure TSystemBaseList<T>.Execute;
  var
    frmList: TfrmBaseList;
  begin
   //frmList := TfrmBaseList.Create(Self<T>)
   //frmList := TfrmBaseList.Create(Self<TSystemColumnEntity>)  
   frmList := TfrmBaseList.Create(???????)
  end;

如何将 TSystemBaseList 传递给 TfrmBaseList 类的构造函数?

这个构造函数只创建一个Form然后将AListOwner赋值给FListOwner, 我可以将此构造函数更改为这样的属性吗:

TfrmBaseList = class(TForm)
private
  FListOwner: TSystemBaseList<TSystemColumnEntity>;
public
  property ListOwner: TSystemBaseList<TSystemColumnEntity> read FListOwner write FListOwner;
end

我该如何设置?

【问题讨论】:

    标签: delphi generics


    【解决方案1】:

    构造函数需要一个具体的实例化,一个实例:

    TSystemBaseList<TSystemColumnEntity>
    

    您提供了一个未实例化的泛型类型实例:

    TSystemBaseList<T>
    

    您必须为该构造函数提供一个具体实例。在其当前形式中,您无法从 TSystemBaseList&lt;T&gt;.Execute 实例化该表单。

    您可能会认为因为T 必须派生自TSystemColumnEntity,所以TSystemBaseList&lt;T&gt; 将与TSystemBaseList&lt;TSystemColumnEntity&gt; 兼容。但事实并非如此,因为不支持通用差异。在此处阅读有关此主题的更多信息:Generics and variance

    一种方法是使表单类型也通用。尽管这与 IDE 表单设计器不兼容。我怀疑需要进行更彻底的重新设计来解决您的问题。我不会就重新设计提供建议,因为我不知道问题所在。

    【讨论】:

    • 我可以将此构造函数更改为属性吗(我编辑了我的问题)?
    • 不,这是完全相同的问题。您只能将未实例化的泛型传递给泛型方法或泛型类的方法或属性或字段。
    • 我有一个带有 Values(TListObject of Generic type) 属性的列表。列表称为表单,它应该选择的行(来自表单上的网格)保存在 List.Values 属性中。出于这个原因,我想将 List 作为所有者(ListOwner 不是组件所有者)发送给 Form,因为 Form 应该有权访问 List.Values 以添加项目。
    • 我回答了你问的问题。
    猜你喜欢
    • 1970-01-01
    • 2023-01-18
    • 2012-10-18
    • 2018-12-18
    • 2020-03-14
    • 2013-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多