program Project2;
{$APPTYPE CONSOLE}
uses SysUtils, Unit1 in 'Unit1.pas';
//定义结构 type
TmyRecord = record name:String; age:Integer; end;
//定义类 TmyClass=class(TObject) Constructor Create(name:String;age:Integer;sex:String); private name:String; age:Integer; sex:String; public procedure Work;
end; TmyEvent=procedure of object; //先定义一个特殊的类型,一个对象所属的过程类型;这是建立事件的前提 {Peoson类} Person=class(TObject)
private Fage:Integer; FOnHundred:TmyEvent; //为刚刚定义的TmyEvent类指定一个变量: FOnHundred procedure setAge(const value:Integer);
public procedure SetOnHundred1; procedure SetOnHundred2; constructor Create; property Age:Integer read Fage write SetAge; property OnHundred:TmyEvent read FOnHundred write FOnHundred; //事件命名一般用on开始
end; // Person类 constructor Person.Create(); begin FOnHundred:= SetOnHundred1;{在对象建立时,我们先让事件调用SetOnHundred1方法} end;
procedure Person.setAge(const value:Integer); begin if (value>0)and (value<200) then Fage:=value; if value=100 then OnHundred; {当输入的年龄是100时,激活事件} end; procedure Person.SetOnHundred1; begin Writeln('OK'); end; procedure Person.SetOnHundred2; begin Writeln('NG'); end;
//类实现 Constructor TmyClass.Create(name:String;age:Integer;sex:String); begin Self.name:=name; Self.age:=age; Self.sex:=sex; end;
procedure TmyClass.Work; begin Writeln(Self.name+','+IntToStr(Self.age)+','+Self.sex); end;
var Rec:TmyRecord; //声明结构 Cls:TmyClass; //声明类 per:Person; begin
//类的调用 Cls:=TmyClass.Create('李斯',18,'男'); Cls.Work();
//结构的调用 Rec.name:='zhangsan'; Rec.age:=18; //使用事件
per:=Person.Create; per.Age:=100; per.FOnHundred:=per.SetOnHundred2; per.Age:=100; per.Free;
Writeln(cls.age); Writeln(cls.name); Writeln(cls.sex);
Writeln(Rec.name); Writeln(Rec.age);
Readln;
end.
|
请发表评论