简体   繁体   中英

how to do Generic like Implementation of class function in delphi

i have a base class and 10 class derived from that class. Base class contain a function that except parameter of type procedure of object . like this

 mytype = procedure (a : integer) of object;

 baseclass = class
 public
   procedure myproc(cont handler : mytype ) ;
 end; 
 procedure baseclass.myproc(cont handler : mytype ) ;
 begin
 // do something
 end;

i am overloading this function in derived class ie derived class contain same function but with different parameter (procedure ( const handler : integer ) of object ). like this

 base1mytype = procedure (a : string) of object; 

 derivedclass1 = class(baseclass)
 public
   procedure myproc(cont handler : base1mytype ) ;overload;
 end;

 base2mytype = procedure (a : boolean) of object; 
 derivedclass1 = class(baseclass)
 public
   procedure myproc(cont handler : base2mytype ) ;overload;
 end;

and so on.........

All i want a generic class that implement this function and i derive my classes from that function eg

   mytype = procedure (a : integer) of object;
    baseclass<T> = class
    public
      procedure myproc(cont handler : T) ;
    end; 
   procedure baseclass<T>.myproc(cont handler : T ) ;
   begin
   // do something
   end;
  and derive classes are like this

deriveclass1  = class<baseclass <string>>
  public
    procedure myproc(cont handler : T) ;
  end;

Since generic constraint does not support constrain of type procedure of object

You need a generic class with an internal type definition:

type
  TBaseClass<T> = class
  public
    type
      THandler = procedure(Arg: T) of object;
  public
    procedure CallHandler(Handler: THandler; Arg: T);
  end;

procedure TBaseClass<T>.CallHandler(Handler: THandler; Arg: T);
begin
  Handler(Arg);
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM