首页 > 解决方案 > Delphi XE4 通用包装器中的无效类型

问题描述

TDictionary<string,T>出于某种原因,我想在 a 周围使用包装器。for但是当我尝试通过编译器迭代地图时说:

[dcc32 Error] Unit1.pas(23): E2010 Incompatible types: 'T' and 'System.Generics.Collections.TPair<System.string,Unit1.TMyMapWrapper<T>.T>'

如何修改泛型类型声明以使这样的简单代码可编译?

这是我的简化代码:

unit Unit1;

interface

implementation

uses
  Generics.Collections
  ;

type
  TMyMapWrapper<T> = class
    private
      fMap : TDictionary<string,T>;
    public
      procedure foo;
  end;

procedure TMyMapWrapper<T>.foo;
var
  item : T;
begin
  for item in fMap do
    ;
end;

end.

标签: delphigenerics

解决方案


如果X是类型TDictionary<A, B>,那么枚举项将是类型TPair<A, B>,而不是B

var
  item: TPair<string, T>;
begin
  for item in fMap do // will compile

如果您只想枚举字典的值(类型T),请使用

var
  val: T;
begin
  for val in fMap.Values do // will compile

推荐阅读