Originale-mail to me for new edition

 

The is operator

 

The is operator, which performs dynamic type checking, is used to verify the actual runtime class of an object. The expression

object is class

returns True if object is an instance of the class denoted by class or one of its descendants, and False otherwise. (If object is nil, the result is False.) If the declared type of object is unrelated to class, that is, if the types are distinct and one is not an ancestor of the others, compilation error results. For example,

if ActiveControl is TEdit then TEdit(ActiveControl).SelectAll;

This statement casts a variable to TEdit after first verifying that the object it references is an instance of TEdit or one of its descendants.

 

Topic groups

 

See also

About class types

Class operators: Overview

Class-reference types

The as operator

 

 

译文

 

is运算符

 

is运算符执行动态类型检查,用于校验对象在运行时真实的类。其用法表达式如下

object is class

这里,如果objectclass表示的类或其后裔类之一,那么表达式返回True,否则返回False。如果objectnil,那么表达式返回False。如果object的声明类型与class无关,即它们二者各自独立并且其中任意一个不是另一个的祖先,那么将导致编译错误。例如,

if ActiveControl is TEdit then TEdit(ActiveControl).SelectAll;

上面的语句在校验对象确实是TEdit类或其后裔类的实例对象之后,把变量转换成为TEdit

 

主题组

 

相关主题

关于类类型

类运算符:概述

类引用类型

as运算符

 

 

编者注

本节中有如下陈述:

如果object的声明类型与class无关,即它们二者各自独立并且其中任意一个不是另一个的祖先,那么将导致编译错误。

经编者考证,上面的陈述是不准确的。例如,下面的代码不会导致编译错误,运行时也不会引发异常。

var

  A: TEdit;

begin

  if A is TObject then

    ShowMessage('A is TObject.')//本行将执行

  else

    ShowMessage('A is not TObject.');

  A := nil;

  if A is TObject then

    ShowMessage('A is TObject.')

  else

    ShowMessage('A is not TObject.');//本行将执行

end;

而下面的代码会导致编译错误:

var

  A: Integer;

begin

  if A is TObject then//本行导致编译错误,因为is作为类运算符不能作用于基本类型Integer

    ShowMessage('A is TObject.')

  else

    ShowMessage('A is not TObject.');

end;

因此,编者认为,原始帮助中的描述应当修正为:

在表达式object  is class 中,假定object的声明类型为TSomeClass,那么,TSomeClassclass二者只要有一个不是类(既不是TObject类,也不是TObject的派生类),那么都会导致编译错误。

显然,is运算符也不能作用于类引用类型。例如,下面的例子将导致编译错误:

type

  TA = class of TObject;

var

  A: TA;

begin

  if A is TA then//导致编译错误

    ShowMessage('A is TA.')

  else

    ShowMessage('A is not TA.');

end;