Delphi中类的自定义事件

2025-04-09 19:03:45

1、打开Delphi7集成开发环境,在默认工程的Form1窗体上放一个Edit1输入框和一个Button1窗体。

Delphi中类的自定义事件

2、在Unit1.pas文件,先定义一个过程类型,再定义一个类,这个类包含上面定义的过旯皱镢涛程类型的变量,代码如下: TProEvent = procedure of object; TTest潮贾篡绐Class = class private FName:string; FScore:string; FOnScoreFull:TProEvent; procedure SetName(const name:string); procedure SetScore(const score:string); public procedure SetOnScoreFull; constructor create; published property Name:string read FName write SetName; property Score:string read FScore write SetScore; property OnScoreFull:TProEvent read FOnScoreFull write FOnScoreFull; end;事件本身也是属性,所以在Published区定义OnScoreFull属性。

Delphi中类的自定义事件

3、接下来我们定义事件的挂载,我们在类的构造函数中就将事件处理方法赋给类的过程类型的字段,代码如下;constructor TTestClass.create;begin FOnScoreFull:=SetOnScoreFull;end;

Delphi中类的自定义事件

4、下面再定义三个方法的实现,代码如下:procedure TTestClass.SetName(const name: string);begin FName:= name;end;procedure TTestClass.SetOnScoreFull; //事件触发执行的方法begin showMessage('成绩不能超过100');end;procedure TTestClass.SetScore(const score: string);begin if StrToInt(score)<=100 then FScore:=score else OnScoreFull; //触发事件end;

Delphi中类的自定义事件

5、双击Button1按钮进入事件方法,并写如下代码:procedure TForm1.Button1Click(Sender: TObject);var mytest:TTestClass;begin mytest:=TTestClass.create; mytest.Name:='李四'; mytest.Score:=Edit1.Text;end;定义了一个TTestClass类的实例,并对Name属性和Score属性进行赋值,当Score>100会触发事件。

Delphi中类的自定义事件

6、F9运行程序,Edit1内输入102,大于100时,会弹出对话框,提示成绩不能大于100

Delphi中类的自定义事件
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢