Delphi - 如何"重载"对象'类型的过程

aka*_*_27 3 delphi overloading delphi-xe4

'Delphi'提供任何方法来'重载''对象'类型的过程,如

TTesting = class(TObject)
Public
Type
TInformationEvent1 = procedure( x: integer ) of object; overload ;
TInformationEvent1 = procedure ( x: integer ; y: string) of object; overload ;
TInformationEvent1 = procedure ( x: integer ; y: string; z: Boolean) of object; overload ;
end
Run Code Online (Sandbox Code Playgroud)

我可以用这三种方式重载这个TInformationEvent1函数吗?

Rud*_*uis 8

不同的类型必须具有不同的名称,因为@ user246408的评论已经说明了.因此,您必须为每个类型指定不同的名称,例如:

type
  TInformationEvent = procedure(X: Integer) of object;
  TInformationEventS = procedure(X: Integer; Y: string) of object;
  TInformationEventSB = procedure(X: Integer; Y: string; Z: Boolean) of object;
Run Code Online (Sandbox Code Playgroud)

现在,您可以将具有匹配签名的任何方法(对象的过程)分配给其中一种类型的实例.因此,您指定方法可能是重载,但类型不能重载.


Ken*_*ran 8

好吧.您可以定义具有相同名称但不同数量的类型参数的泛型类型.

type
  TInformationEvent<T> = procedure(x:T) of object;
  TInformationEvent<T1,T2> = procedure(x:T1;y:T2) of object;
  TInformationEvent<T1,T2,T3> = procedure(x:T1; y:T2; z:T3) of object;
Run Code Online (Sandbox Code Playgroud)

然后,当您将其中一个作为类的成员添加时,您需要解析类型参数.

type
  TMyClass = class
  private
    FMyEvent: TInformationEvent<Integer>;
    FMyEvent2: TInformationEvent<Integer,string>;
  public
    property MyEvent: TInformationEvent<Integer> read FMyEvent write FMyEvent;
    property MyEvent2: TInformationEvent<Integer,string> read FMyEvent2 write FMyEvent2;
  end;
Run Code Online (Sandbox Code Playgroud)

就编译器而言,这些在技术上是不同的命名类型,但从开发人员的角度来看,您不需要为每种类型提供唯一的名称.请注意,overload关键字的使用是不必要的,实际上是在定义过程类型时使用的语法错误.Overload具有非常特殊的含义:ad hoc多态.这不是它.

请注意,如果您正在编写组件或控件并希望制作这些已发布的属性,则您的里程可能会有所不同 表单设计师对泛型有很多支持.