Delphi的属性Property

本文介绍了如何在Delphi中使用读写属性、只读属性和事件回调函数进行数据操作。通过实例展示了如何定义属性、构造函数、修改属性值以及调用事件回调函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考:http://www.cnblogs.com/edisonfeng/archive/2012/05/22/2513727.html

一、基本属性

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

  对于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;
    Slef.Memo1.Font.Color:= clGreen;
    Self.theUserInfo.OnUserInfoShow:= Self.USerInfoShow;
end;

调用事件回调函数

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

运行

转载于:https://www.cnblogs.com/xumenger/p/4422910.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值