Originale-mail to me for new edition

 

Class-reference types

 

A class-reference type, sometimes called a metaclass, is denoted by a construction of the form

class of type

where type is any class type. The identifier type itself denotes a value whose type is class of type. If type1 is an ancestor of type2, then class of type2 is assignment-compatible with class of type1. Thus

type TClass = class of TObject;

var AnyObj: TClass;

declares a variable called AnyObj that can hold a reference to any class. (The definition of a class-reference type cannot occur directly in a variable declaration or parameter list.) You can assign the value nil to a variable of any class-reference type.

   To see how class-reference types are used, look at the declaration of the constructor for TCollection (in the Classes unit):

type TCollectionItemClass = class of TCollectionItem;

  ...

constructor Create(ItemClass: TCollectionItemClass);

This declaration says that to create a TCollection instance object, you must pass to the constructor the name of a class descending from TCollectionItem.

Class-reference types are useful when you want to invoke a class method or virtual constructor on a class or object whose actual type is unknown at compile time.

 

Constructors and class references

 

Topic groups

 

See also

Class references: Overview

 

 

译文

 

类引用类型

 

类引用类型有时叫做元类(metaclass),表示类引用类型的结构具有如下形式

class of type

这里的type是任何类类型。标识符type自身表示一个值,它的类型是type类。如果type1type2的祖先,那么type2的类与type1的类是赋值兼容的。因此,

type TClass = class of TObject;

var AnyObj: TClass;

这里声明一个叫做AnyObj的变量,用于可以保存对任何类的引用。(类引用类型的定义不能直接出现在变量声明或参数列表声明中。)可以把值nil赋给任何类引用类型的变量。

要明白类引用类型是如何被使用的,可以查看TCollectionClasses单元中)的构造器声明:

type TCollectionItemClass = class of TCollectionItem;

  ...

constructor Create(ItemClass: TCollectionItemClass);

这里的声明表明,要创建TCollection的实例对象,就必需向构造器传递TCollectionItem类或自该类派生的类的名称。

编译时,想要调用类或对象的类方法或者虚拟的构造器,而不知道其实际类型时,类引用类型是有用的。

 

构造器和类引用

 

主题组

 

相关主题

类引用:概述