A field is like a variable that
belongs to an object. Fields can be of any type, including class types. (That
is, fields can hold object references.) Fields are usually private.
To define a field member of a
class, simply declare the field as you would a variable. All field declarations
must occur before any property or method declarations. For example, the
following declaration creates a class called TNumber whose only member,
other than the methods is inherits from TObject, is an integer field
called Int.
type
TNumber = class
Int: Integer;
end;
Fields are statically bound; that
is, references to them are fixed at compile time. To see what this means,
consider the following code.
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
TDescendant(MyObject).Value := 'Hello!'; // works!
end;
Although MyObject holds an instance of TDescendant, it is declared as TAncestor. The compiler therefore interprets MyObject.Value as referring to the (integer) field declared in TAncestor. Both fields, however, exist in the TDescendant object; the inherited Value is hidden by the new one, and can be accessed through a typecast.
对于对象来说,一个域就象一个变量。域可以是任何类型,包括类类型。(也就是说,域可以保存对象引用。)域通常是私有的。
要定义类的域成员,只需简单地象声明变量那样声明域。所有的域声明必需出现在任何属性或方法声明之前。例如,先面的声明创建了一个叫做TNumber的类,该类中除继承自TObject的方法之外,仅有一个叫做Int的整数域成员。
type
TNumber = class
Int: Integer;
end;
域的范围是静态的,即编译时对域的引用是固定的。要明白这一含义,考虑如下代码:
type
TAncestor = class
Value: Integer;
end;
TDescendant = class(TAncestor)
Value: string; //隐藏了继承得到的Value域
end;
var
MyObject: TAncestor;
begin
MyObject := TDescendant.Create;
MyObject.Value := 'Hello!';
//错误
TDescendant(MyObject).Value := 'Hello!'; //正常工作
end;
尽管MyObject保存了TDescendant的一个实例,它声明为TAncestor,但编译器仍将MyObject.Value解释为对TAncestor中声明的整数域的引用。不过,在TDescendant实例对象
中仍然存在两个域,只是继承得到的Value域被新的域隐藏而已,可以通过类型转换访问前者。