Delphi - 如何将Generic参数传递给接受const参数数组的函数

aka*_*_27 5 delphi generics delphi-xe4

我有一个'基类',它包含一个'函数',接受'Array of const'类型的参数,如下所示: -

type
  TBaseClass = class(TObject)
  public
    procedure NotifyAll(const AParams: array of const);
  end;

procedure TBaseClass.NotifyAll(const AParams: array of const);
begin
  // do something
end;
Run Code Online (Sandbox Code Playgroud)

我有另一个'通用类'派生自'基类'(上面定义)

type
  TEventMulticaster<T> = class(TBaseClass)
  public
    procedure Notify(AUser: T); reintroduce;
  end;

procedure TEventMulticaster<T>.Notify(AUser: T);
begin
  inherited NotifyAll([AUser]);   ERROR HERE
end;
Run Code Online (Sandbox Code Playgroud)

每次我编译这段代码时都会出错:

变量类型数组构造函数中的错误参数类型

它指的是什么错?

Dav*_*nan 5

您不能将通用参数作为变体开放数组参数传递。语言泛型支持根本无法满足这一点。

您可以做的是将 Generic 参数包装在一个变体类型中,例如TValue. 现在,您也不能TValue在变体开放数组参数中传递实例,但您可以更改NotifyAll()为接受以下开放数组TValue

procedure NotifyAll(const AParams: array of TValue);
Run Code Online (Sandbox Code Playgroud)

一旦你有了这个,你可以从你的通用方法中调用它,如下所示:

NotifyAll([TValue.From<T>(AUser)]);
Run Code Online (Sandbox Code Playgroud)

从根本上说,您在这里尝试做的是将编译时参数差异(泛型)与运行时参数差异相结合。对于后者,有多种选择。变体开放数组参数就是这样一种选择,但它们不能很好地与泛型配合使用。我在这里建议的替代方案TValue,确实与泛型具有良好的互操作性。