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;

  //TMyClass1 类里面只有两个字段(变量来到类里面称做字段)
  TMyClass1 = class
    FName: string;  {字段命名一般用 F 开头, 应该是取 field 的首字母}
    FAge:  Integer; {另外: 类的字段必须在方法和属性前面}
  end;
  {这个类中的两个字段, 可以随便读写; 在实际运用中, 这种情况是不存在的.}


  //TMyClass2 类里面包含两个属性(property)、两个方法、两个和 TMyClass1 相同的字段
  TMyClass2 = class
  strict private
    FName: string;
    FAge:  Integer;
    procedure SetAge(const Value: Integer);
    procedure SetName(const Value: string);
  published
    property Name: string  read FName write SetName;
    property Age:  Integer read FAge  write SetAge;
  end;
  {
    但这里的字段: FName、FAge 和方法: SetAge、SetName 是不能随便访问的,
    因为, 它们在 strict private 区内, 被封装了, 封装后只能在类内部使用.

    属性里面有三个要素:
    1、指定数据类型: 譬如 Age 属性是 Integer 类型;
    2、如何读取: 譬如读取 Age 属性时, 实际上读取的是 FAge 字段;
    3、如何写入: 譬如希尔 Age 属性时, 实际上是通过 SetAge 方法.

    属性不过是一个桥.

    通过属性存取字段 和 直接存取字段有什么区别?
    通过属性可以给存取一定的限制,
    譬如: 一个人的 age 不可能超过 200 岁, 也不会是负数; 一个人的名字也不应该是空值.

    看 implementation 区 TMyClass2 类的两个方法的实现, 就增加了这种限制.
   }

var
  Form1: TForm1;

implementation

{$R *.dfm}


{ TMyClass2 }

procedure TMyClass2.SetAge(const Value: Integer);
begin
  if (Value>=0) and (Value<200) then
    FAge := Value;
end;

procedure TMyClass2.SetName(const Value: string);
begin
  if Value<>'' then
    FName := Value;
end;


//测试:
procedure TForm1.Button1Click(Sender: TObject);
var
  class1: TMyClass1;
  class2: TMyClass2;
begin
  class1 := TMyClass1.Create;
  class2 := TMyClass2.Create;

  class1.FAge := 1000; {TMyClass1 中的 FAge 字段可以接受一个离奇的年龄}
  class2.Age  := 99;   {通过 TMyClass2 中的 Age 属性, 只能赋一个合理的值}
  //class2.FAge := 99; {TMyClass2 中的 FAge 字段被封装了, 在这里无法使用}

  class1.Free;
  class2.Free;
end;

end.

posted on 2008-01-11 02:22  万一  阅读(7815)  评论(8编辑  收藏  举报