Delphi (XE7) 添加泛型 class 到泛型 TDictionary
Delphi (XE7) add Generic class to generic TDictionary
在下面的代码中:
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 Error] Unit1.pas(35): E2010 Incompatible types:
'Unit1.TMyClass' and
'Unit1.TMyClass.T>'
在我试图将 Self 添加到 TDictionary 的行中。如何将泛型 class 添加到 TDictionary,其中第二个参数采用泛型对象?
虽然您的约束确保 T
只能是 TForm
,但编译器不支持所谓的协方差。
您可以做的是将 Self
强制转换为 TMyClass<TForm>
以添加它。
在下面的代码中:
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 Error] Unit1.pas(35): E2010 Incompatible types: 'Unit1.TMyClass' and 'Unit1.TMyClass.T>'
在我试图将 Self 添加到 TDictionary 的行中。如何将泛型 class 添加到 TDictionary,其中第二个参数采用泛型对象?
虽然您的约束确保 T
只能是 TForm
,但编译器不支持所谓的协方差。
您可以做的是将 Self
强制转换为 TMyClass<TForm>
以添加它。