as,is是用来判断和转换子类和父类
is是判断A类是不是B类的子类 返回True 或 False
objectName(同类 或 子类) is className (父类)
左方的Object对象是否属于右方的Class类
当返回为True时,就可以用 as 操作数来将左方的对象由原来所属的类,转为右方
操作数那种类.
ad,is 的结合使用,不仅能对转型前的判断和结下来的是否转换,
还可以,将不同类型(TLabel, TEdit)的组件类型,分别做相应的处理,
如此,不仅代码简洁,对同类组件做相同处理,还可以省去指定各组件的麻烦,
也能确保对同类型组件处理的统一性.
Code
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Panel1: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Panel2: TPanel;
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Edit4: TEdit;
Edit5: TEdit;
Edit6: TEdit;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
VAR
I: Integer;
j: Integer;
begin
FOR I := 0 TO form1.ControlCount - 1 DO // Iterate
BEGIN
IF form1.Controls[i] IS TPanel THEN
BEGIN
IF form1.Controls[i] = Panel1 THEN
BEGIN
(form1.Controls[i] as TPanel).Color := RGB(255, 0, 0);
FOR J := 0 TO Panel1.ControlCount - 1 DO // Iterate
IF Panel1.Controls[j] IS TLabel THEN
BEGIN
(Panel1.Controls[J] as TLabel).Color := RGB(255, 255, 0);
(Panel1.Controls[J] as TLabel).Font.Style := [fsUnderLine];
END;
END;
IF form1.Controls[i] = Panel2 THEN
BEGIN
(form1.Controls[i] as TPanel).Color := RGB(0, 0, 255);
FOR J := 0 TO Panel2.ControlCount - 1 DO // Iterate
IF Panel2.Controls[j] IS TEdit THEN
(Panel2.Controls[J] as TEdit).Text := '';
END;
END;
END; // for I
end;
end.