unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}


type
  TStr12 = string[12]; {属性不接受 string[12], 只好定义成一个类型或使用 ShortString}

  TRec = record    {定义结构 TRec}
  strict private   {如果不使用 strict 修饰符, 在同一单元内的私有变量也是可以访问的}
    Fname: TStr12;
    Fage: Word;
    procedure Setage(const Value: Word);
    procedure Setname(const Value: TStr12);
  public
    property name: TStr12 read Fname write Setname;
    property age: Word read Fage write Setage;
  end;


{ TRec 属性要调用的方法实现}

procedure TRec.Setname(const Value: TStr12);
begin
  if Value='' then  {这时可以提出一些条件, 譬如譬如姓名不能为空}
  Fname := '无名氏'
  else Fname := Value;
end;

procedure TRec.Setage(const Value: Word);
begin
  if (Value<150) and (Value>=0) then  {这时可以提出一些条件, 譬如年龄一般不会超过 150}
    Fage := Value
  else Fage := 0;
end;



//使用结构
procedure TForm1.Button1Click(Sender: TObject);
var
  rec: TRec;
begin
  rec.name := '张三'; {现在的 name 和 age 已经是属性了}
  rec.age := 800;

  ShowMessage(rec.name);          {张三}
  ShowMessage(IntToStr(rec.age)); {0}


  rec.name := '';
  rec.age := 18;

  ShowMessage(rec.name);          {无名氏}
  ShowMessage(IntToStr(rec.age)); {18}
end;

end.

posted on 2008-01-09 16:03  万一  阅读(3676)  评论(5编辑  收藏  举报