运行时点击按钮出现list index out of bounds(3),之后是list index out of bounds(2),再按则正常,什么问题呢?
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls;
type
TControlClass=class of TControl;
TForm1 = class(TForm)
MonthCalendar1: TMonthCalendar;
Memo1: TMemo;
ColorBox1: TColorBox;
RadioGroup1: TRadioGroup;
Button1: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
procedure createControlObj(ControlClass:TControlClass);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.createControlObj(ControlClass:TControlClass);
var AControlObj:TControl;
begin
AControlObj:=ControlClass.Create(self);//根据不同的类类型,动态创建对象
AControlObj.Parent:=self;//指定TForm1为控件的容器
AControlObj.Name:=AControlObj.ClassName;//以类名作为控件名
AControlObj.SetBounds(10,10,250,150);//设置控件边界
Label1.Caption:=AControlObj.ClassName;
end;
procedure TForm1.Button1Click(Sender: TObject);
const
//定义一个以控件类类型为元素的数组
ContrlClassArry:array[0..2] of
TControlClass=(TMonthCalendar,TMemo,TColorBox);
var
i:Integer;
begin
//清空已经动态生成的控件
for i := 0 to controlcount-1 do
if (Controls[i] is TMonthCalendar) or (Controls[i] is TMemo)
or (Controls[i] is TColorBox) then
Controls[i].Free;
//调用构造函数,动态生成用户选定的控件
createControlObj(ContrlClassArry[RadioGroup1.ItemIndex]);
end;
end.