【问题标题】:Delphi (XE7) add Generic class to generic TDictionaryDelphi (XE7) 将泛型类添加到泛型 TDictionary
【发布时间】:2016-11-21 14:21:17
【问题描述】:

在以下代码中:

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Generics.Collections;

type
  TForm1 = class(TForm)
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  TMyClass<T: TForm> = class
  public
    constructor Create;
  end;

var
  Form1: TForm1;
  List: TDictionary<integer, TMyClass<TForm>>;

implementation

{$R *.dfm}


{ TMyClass<T> }

constructor TMyClass<T>.Create;
begin
  List.Add(1, self);
end;

end.

我得到错误:

[dcc32 错误] Unit1.pas(35): E2010 不兼容的类型: 'Unit1.TMyClass' 和 'Unit1.TMyClass.T>'

在我尝试将 Self 添加到 TDictionary 的位置。如何将泛型类添加到 TDictionary,其中第二个参数采用泛型对象?

【问题讨论】:

    标签: delphi generics delphi-xe7


    【解决方案1】:

    虽然您的约束是确保 T 只能属于 TForm,但编译器不支持所谓的协方差。

    您可以做的是将Self 硬转为TMyClass&lt;TForm&gt; 以添加它。

    【讨论】:

    • 谢谢。有趣的是:变量“List”必须在接口内部,而不是实现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 2014-12-19
    相关资源
    最近更新 更多