Delphi - How can I pass Generic parameter to function that accept Array of const parameter

本小妞迷上赌 提交于 2019-12-12 11:05:47

问题


I have a 'Base class' which contain a 'function' that accept parameter of type 'Array of const' as shown below:-

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;

I have another 'Generic class' that is derived from the 'base class' ( defined above )

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;

Every time I compile this code it gives error saying:

Bad argument type in variable type array constructor

What does it referring to be wrong?


回答1:


You cannot pass a generic argument as a variant open array parameter. The language generics support simply does not cater for that.

What you can do is wrap the generic argument in a variant type. For instance TValue. Now, you cannot pass TValue instances as as a variant open array parameters either, but you can change NotifyAll to accept an open array of TValue instead.

procedure NotifyAll(const AParams: array of TValue);

Once you have this in place you can call it from your generic method like so:

NotifyAll([TValue.From<T>(AUser)]);

Fundamentally what you are attempting to do here is combine compile time parameter variance (generics) with run time parameter variance. For the latter there are various options. Variant open array parameters are one such option, but they do not play well with generics. The alternative that I suggest here, TValue, does have good interop with generics.



来源:https://stackoverflow.com/questions/26584559/delphi-how-can-i-pass-generic-parameter-to-function-that-accept-array-of-const

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!