1

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

"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 acestor:

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

并有这个构造函数:

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

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

如何修复此代码?

4

1 回答 1

3

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

您的IEqualityComparer<T>示例中的来自Spring.Tests.Interception.Types.pas. 构造函数中使用的TMultiMap<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 测试

于 2021-02-09T21:26:26.450 回答