Delphi - How to pass a Generic parameter to a function that takes an Array of a const parameter

I have a "base class" that contains a "function" that takes a 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 โ€œcommon classโ€ that is derived from a 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 an error:

Bad argument type in array type constructor constructor

What does it mean to be wrong?

+5
source share
1 answer

You cannot pass a general argument as a variant of an open array . Support for native speakers is simply not suitable for this.

What you can do is wrap the general argument into a variant type. For example TValue . Now you cannot pass instances of TValue as parameters to the open array variant, but you can modify NotifyAll to accept the open TValue array TValue .

 procedure NotifyAll(const AParams: array of TValue); 

Once you do this, you can call it from your general method as follows:

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

Basically, you are trying to do this; it is a combination of generics parameters with the variance of the runtime parameter. There are various options for the latter. Variant open array options are one of those options, but they don't mix well with generics. The alternative that I offer here, TValue , has a good interaction with generics.

+3
source

Source: https://habr.com/ru/post/1205594/


All Articles