unit Unit1;
interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;
type //定义一个事件格式,要传参数的格式 后面必须要加上of object TeacherArgnyEvent = procedure(ErrorCount: Integer) of object;
type TTeacher = class(TObject) private FStudentErrorCount: Integer; FOnTeacherArngy: TeacherArgnyEvent; //定义一个内部事件,private里的只能在TTeacher类内部调用 procedure SetStudentErrorCount(Value: Integer); public constructor Create; destructor Destroy; override; property StudentErrorCount: Integer read FStudentErrorCount write SetStudentErrorCount ; property OnTeacherArngy: TeacherArgnyEvent read FOnTeacherArngy write FOnTeacherArngy ; //定义一个外部的事件,在其它的对象里面可以通过FTeacher.ONTeacherArngy这样调用。读写是通过内部的FOnTeacherArngy end;
type TForm1 = class(TForm) Button1: TButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Button1Click(Sender: TObject); procedure IfTeacherArngy(EC: Integer); //自己定义事件触发时要执行的函数,和Button控件在事件列表中双击时出来的那段代码一样,只是这里是你自己定义的,而不是DELPHI给你生成的 private FTeacher: TTeacher ; public { Public declarations } end;
var Form1: TForm1;
implementation
{$R *.dfm}
{ TTeacher }
constructor TTeacher.Create; begin FStudentErrorCount := 0; end;
destructor TTeacher.Destroy; begin
inherited; end;
procedure TTeacher.SetStudentErrorCount(Value: Integer); begin FStudentErrorCount := Value; if FStudentErrorCount > 3 then //给StudentErrorCount赋值的时候,判断是否触发FOnTeacherArngy事件 if Assigned(FOnTeacherArngy) then //看FOnTeacherArngy是否为空,不为空则执行该事件,如果不判断是否为空,则执行下面一句的时候可能会有错误 FOnTeacherArngy(FStudentErrorCount); end;
{ TForm }
procedure TForm1.FormCreate(Sender: TObject); begin FTeacher := TTeacher.Create ; //创建一个TTeacher的实例 FTeacher.OnTeacherArngy := IfTeacherArngy; //把FOrm1里的IfTeacherArngy过程赋值给FTeacher的OnTeacherArngy,这样它就不为空了 end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin FTeacher.Free ; //窗体关闭时释放 end;
procedure TForm1.Button1Click(Sender: TObject); begin FTeacher.StudentErrorCount := FTeacher.StudentErrorCount + 1; //给StudentErrorCount赋值 ,我只是给他赋值,就会触发那个事件 // 有了这个类,就不用下面这一段了,给 StudentErrorCount属性赋值就能达到下面这段代码的效果。 // if FTeacher.StudentErrorCount > 3 then // ShowMessage('Student 错误了' + IntToStr(ec) + '次,老师生气了。'); end;
procedure TForm1.IfTeacherArngy(EC: Integer); begin ShowMessage('Student 错误了' + IntToStr(ec) + '次,老师生气了。'); //事件触发时的情况,和Button控件在事件列表中双击时出来的那段代码一样,只是这里是你自己定义的,而不是DELPHI给你生成的 end;
end.
|
请发表评论