编译器看不到 Spring4D TMultiMap 重载构造函数(错误 E2250)

Spring4D TMultiMap overloaded constructor not seen by compiler (Error E2250)

我正在努力使用 Spring4D (1.2.2) TMultiMap 泛型 class。我想调用一个重载的构造函数,编译器抱怨:

"E2250 There is no overloaded version of 'Create' that can be called with these arguments"

根据 Spring4D 源代码,参数是正确的类型。

我设计了一个重现错误的小程序:

program Spring4DMultiMapTest;

{$APPTYPE CONSOLE}

{$R *.res}

uses
    System.SysUtils,
    Generics.Collections,
    Spring.Tests.Interception.Types,
    Spring.Collections.MultiMaps,
    Spring.Collections;

type
    TMyKey = TPair<Double, Integer>;

    TMyKeyEqualityComparer = class(TInterfacedObject, IEqualityComparer<TMyKey>)
        function Equals(const Left, Right: TMyKey): Boolean; reintroduce;
        function GetHashCode(const Value: TMyKey): Integer; reintroduce;
    end;

function TMyKeyEqualityComparer.Equals(const Left, Right: TMyKey): Boolean;
begin
    if Left.Key < (Right.Key - 1E-9) then
        Result := TRUE
    else if Left.Key > (Right.Key + 1E-9) then
        Result := FALSE
    else if Left.Value < Right.Value then
        Result := TRUE
    else
        Result := FALSE;
end;

function TMyKeyEqualityComparer.GetHashCode(const Value: TMyKey): Integer;
begin
    Result := Value.Value + Round(Value.Key * 1E6);
end;

var
    Events      : IMultiMap<TMyKey, Integer>;
    KeyComparer : IEqualityComparer<TMyKey>;
begin
    KeyComparer := TMyKeyEqualityComparer.Create;
    // Next line triggers error: "E2250 There is no overloaded version of 'Create' that can be called with these arguments"
    Events := TMultiMap<TMyKey, Integer>.Create(KeyComparer);
end.

在Spring4D源码中,我发现如下声明:

TMultiMap<TKey, TValue> = class(TMultiMapBase<TKey, TValue>)

并且还声明了 TMultiMap 祖先:

  TMultiMapBase<TKey, TValue> = class abstract(TMapBase<TKey, TValue>,
    IMultiMap<TKey, TValue>, IReadOnlyMultiMap<TKey, TValue>)

并且有这个构造函数:

constructor Create(const keyComparer: IEqualityComparer<TKey>); overload;

这是我要调用的构造函数。据我了解,我的论点 KeyComparer 具有正确的类型。但显然编译器不同意:-(

如何修复此代码?

您使用了不同的 IEqualityComparer<T> 类型。

您示例中的 IEqualityComparer<T> 来自 Spring.Tests.Interception.Types.pasTMultiMap<TKey, TValue>.Create 构造函数中使用的那个在 System.Generics.Defaults.pas.

中定义

如果您将 uses 部分更改为

uses
    System.SysUtils,
    Generics.Collections,
    // Spring.Tests.Interception.Types,
    Generics.Defaults,
    Spring.Collections.MultiMaps,
    Spring.Collections;

您的示例将编译。

使用 Delphi 10.3 U3 和 Spring4D 1.2.2 测试