Delphi语言学习8-类成员(字段和方法)2011-12-121.Class Fields
//例1 成员变量
type
TAncestor = class
Value: Integer;
end;
TDescendant = class(TAncestor)
Value: string;// hides the inherited Value field
end;
var
MyObject: TAncestor;
begin
MyObject := TDescendant.Create;
MyObject.Value := "Hello!" // error
(MyObject as TDescendant).Value := "Hello!" // works!
end;
//例2 静态字段
type
TMyClass = class
public
class var// Introduce a block of class static fields.
Red: Integer;
Green: Integer;
Blue: Integer;
var// Ends the class var block.
InstanceField: Integer;
end;
//静态字段可以单独调用
TMyClass.Red := 1;
TMyClass.Green := 2;
TMyClass.Blue := 3;
//静态字段也可以通过对象实例调用
var
myObject: TMyClass;
myObject.Red := 1;
myObject.Green := 2;
myObject.Blue := 3;
2.Method Binding
//Static Methods
//例1
type
TFigure = class
procedure Draw;
end;
TRectangle = class(TFigure)
procedure Draw;
end;
var
Figure: TFigure;
Rectangle: TRectangle;
begin
Figure := TFigure.Create;
Figure.Draw;// calls TFigure.Draw
Figure.Destroy;
Figure := TRectangle.Create;
Figure.Draw;// calls TFigure.Draw
TRectangle(Figure).Draw;// calls TRectangle.Draw
Figure.Destroy;
Rectangle := TRectangle.Create;
Rectangle.Draw;// calls TRectangle.Draw
Rectangle.Destroy;
end;
//虚方法和动态方法
type
TFigure = class
procedure Draw; virtual;
end;
TRectangle = class(TFigure)
procedure Draw; override;
end;
TEllipse = class(TFigure)
procedure Draw; override;
end;
var
Figure: TFigure;
begin
Figure := TRectangle.Create;
Figure.Draw;// calls TRectangle.Draw
Figure.Destroy;
Figure := TEllipse.Create;
Figure.Draw;// calls TEllipse.Draw
Figure.Destroy;
end;
//例2
type
T1 = class(TObject)
procedure Act; virtual;
end;
T2 = class(T1)
procedure Act; // Act is redeclared, but not overridden
end;
var
SomeObject: T1;
begin
SomeObject := T2.Create;
SomeObject.Act;// calls T1.Act
end;
//类方法 Class Method
//Ordinary Class Methods
//The definition of a class method must begin with the reserved word class. For example,
type
TFigure = class
public
class function Supports(Operation: string): Boolean; virtual;
class procedure GetInfo(var Info: TFigureInfo); virtual;
end;
//The defining declaration of a class method must also begin with class. For example,
class procedure TFigure.GetInfo(var Info: TFigureInfo);
begin
end;
//Class Static Methods
type
TMyClass = class
strict private
class var
FX: Integer;
strict protected
// Note: accessors for class properties must be declared class static.
class function GetX: Integer; static;
class procedure SetX(val: Integer); static;
public
class property X: Integer read GetX write SetX;
class procedure StatProc(s: String); static;
end;
//调用
TMyClass.X := 17;
TMyClass.StatProc("Hello");