Delphi – 如何将Generic参数传递给接受const参数数组的函数
发布时间:2020-12-15 04:14:03 所属栏目:大数据 来源:网络整理
导读:我有一个’基类’,它包含一个’函数’,接受’Array of const’类型的参数,如下所示: – type TBaseClass = class(TObject) public procedure NotifyAll(const AParams: array of const); end;procedure TBaseClass.NotifyAll(const AParams: array of const
我有一个’基类’,它包含一个’函数’,接受’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; 我有另一个’通用类’派生自’基类'(上面定义) 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; 每次我编译这段代码时都会出错:
它指的是什么错? 解决方法
您不能将通用参数作为
variant open array parameter传递.语言泛型支持根本不能满足这一要求.
您可以做的是将泛型参数包装在变体类型中.例如TValue.现在,您也无法将TValue实例作为变量打开数组参数传递,但您可以将NotifyAll更改为接受一个开放的TValue数组. procedure NotifyAll(const AParams: array of TValue); 一旦你有了这个,你可以从你的通用方法调用它,如下所示: NotifyAll([TValue.From<T>(AUser)]); 从根本上说,您在此尝试的是将编译时参数方差(泛型)与运行时参数方差相结合.对于后者,有各种选择.变体开放数组参数就是这样一个选项,但它们与泛型不匹配.我在这里建议的另一种选择,TValue,确实与泛型有很好的互操作性. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |