类:认识类的封存装

ContractedBlock.gifExpandedBlockStart.gifCode
unit Unit1;

interface

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

type
  TForm1 
= class(TForm)
    Button1: TButton;
    
procedure Button1Click(Sender: TObject);
  
private
    
{ Private declarations }
  
public
    
{ Public declarations }
  
end;
  
//这个类中的两个字段没有封装
  TMyClass 
= class
    FName: 
string;
    FAge: Integer;
  
end;
  
//这个类中的两个字段封装了,外部不能读写
  TMyClass2 
= class
  
private
    FName: 
string;
    FAge: Integer;
  
end;
  
//那怎么读写?用属性啊!
  TMyClass3 
= class
  
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;
  
(*
    * 现在 TMyClass3 中的两上字段:FName, FAge 和两个方法:SetAge,SetName
    * 都被封装在私有区 private 内,不允许外部读写,只能是内部调用。
    * 不过,private的封装在本单元内是无效的!
    * 现在好了,有了strict 标识符。
  
*)
  TMyClass4 
= 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;


var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TMyClass3 }

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

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

{ TMyClass4 }

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

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

procedure TForm1.Button1Click(Sender: TObject);
var
  Class3: TMyClass3;
  Class4: TMyClass4;
begin
  Class3 :
= TMyClass3.Create; //Class3. 后面可以看到 FName,FAge,SetAge,SetName
  Class4 :
= TMyClass4.Create; //Class4. 后面就看不到 FName,FAge,SetAge,SetName
  Class4.Name :
= 'eboy';
  Class4.Age :
= '99';
  Class3.Free;
  Class4.Free;
end;

end.

转载于:https://www.cnblogs.com/jxgxy/archive/2009/11/13/1602607.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值