property的使用【Delphi版】

一.基本声明

 TOnUserInfoShow = procedure(userName:string;userAge:Integer)of object;//定义事件模型中的回调函数原型

  TUserInfo = class
    private
      FName:string;
      FAge:Integer;
      FOnUserInfoShow: TOnUserInfoShow;

      procedure FSetAge(theAge:Integer);
    public
      property Name:string read FName;//只读属性(私有变量)
      property Age:Integer read FAge write FSetAge;//读写属性(私有变量,私有方法)

      property OnUserInfoShow:TOnUserInfoShow  read FOnUserInfoShow write FOnUserInfoShow;//事件模型回调函数

      constructor Create;
  end;

     Ps: 对于FAge,FSetAge等变量和方法,只需在property后声明好,直接Ctrl+shift+c,即可自动生成。

二.只读属性

     构造函数

constructor TUserInfo.Create;
begin
   Self.FName:='Terry';
   Self.FAge:=20;
end;

    读取只读属性

begin
  Self.Memo1.Lines.Add('读取只读属性姓名:'+Self.theUserInfo.Name);
end;

    运行

   

 

三.读写属性

    构造函数

constructor TUserInfo.Create;
begin
   Self.FName:='Terry';
   Self.FAge:=20;
end;

    修改读写属性,并读取新值

begin
   Self.Memo1.Lines.Add('修改前的读写属性年龄为:'+inttostr(Self.theUserInfo.Age));
   Self.theUserInfo.Age:=30;
   Self.Memo1.Lines.Add('修改后的读写属性年龄为:'+inttostr(Self.theUserInfo.Age));
end;

    运行

  

四.事件回调函数

    主窗体成员函数

procedure TFrmMain.UserInfoShow(name: string; age: Integer);
begin
   Self.Memo1.Lines.Add('用户姓名为:'+Self.theUserInfo.Name);
   Self.Memo1.Lines.Add('用户年龄为:'+inttostr(Self.theUserInfo.Age));
end;

   主窗体创建时,将函数指针赋值给“事件回调函数”

procedure TFrmMain.FormCreate(Sender: TObject);
begin
   Self.Memo1.Color:=clBlack;
   Self.Memo1.Font.Color:=clGreen;
   theUserInfo:=TUserInfo.Create;
   Self.theUserInfo.OnUserInfoShow:=Self.UserInfoShow;
end;

  调用事件回调函数

begin
   Self.theUserInfo.OnUserInfoShow(Self.theUserInfo.Name,Self.theUserInfo.Age);
end;

  运行

 

 

转载于:https://www.cnblogs.com/edisonfeng/archive/2012/05/22/2513727.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值