Delphi中类的自定义事件

 时间:2024-10-18 01:26:19

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

Delphi中类的自定义事件

2、在Unit1.pas文件,先定义一个过程类型,再定义一个类,这个类包含上面定义的过程类型的变量,代码如下: TProEvent = procedure of object; TTestClass = 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中类的自定义事件
  • 如何缩短项目交付周期
  • pycharm怎么取消自动换行
  • notepad++如何创建一个简单的HTML程序
  • 如何查看电脑迅雷的版本号
  • 怎么让win7任务栏图标不合并
  • 热门搜索
    河北民族师范学院怎么样 中国怎么 qq赞怎么刷 深圳火车站在哪里 如何让男人兴奋 如何治疗脚气 如何快速赚钱 张家界旅游多少钱 浙江横店旅游攻略 如何白发变黑发