首页  编辑  

运行的时候,创建任意的对象?

Tags: /超级猛料/Language.Object Pascal/面向对象和类、VCL核心/   Date Created:

我希望在运行的时候,创建任意的对象,例如:TButton,TLabel,TImage等等......怎么办?

请参考下面的代码:

Russar <russar@wp.pl>提问

uses typinfo ;

const

 Buffer : array [ 0 .. 3 ] of TComponentClass =( TBitBtn , TLabel , TButton , TSpeedButton );

procedure CreateObjectInstance ( AClass : TComponentClass ; Var Ref ; AOwner : TComponent );

begin

 TComponent ( Ref ):= TComponent ( AClass . NewInstance );

  try

   TComponent ( Ref ). Create ( AOwner );

  except

   TObject ( Ref ):= nil ;

    Raise ;

  end ;

end ;

procedure TForm1 . Button1Click ( Sender : TObject );

var

 Obj : TComponent ;

 i : integer ;

begin

  for i := Low ( Buffer ) to High ( Buffer ) do

  begin

   CreateObjectInstance ( Buffer [ i ], Obj , Self );

   TControl ( Obj ). Parent := Self ;

   SetPropValue ( Obj , 'Top' , i * 30 );

   SetPropValue ( Obj , 'Caption' , 'Test' );

  end ;

end ;