Delphi 系统[26]关键字和保留字 of、as、is
1、定义:
- of :用于和其他关键字构成指定的结构。of可以与 case, class, array, file, set, object 连用。
- as :用于将一个类对象当作另一种类型使用。
- is :用于判断对象是否属于某一类型。
2、示例:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
{ of 关键字 }type TMyClass = class of TEdit; TMyFun = function(I: Integer): Integer of Object;procedure TForm1.Button1Click(Sender: TObject);var MyArr : array of Integer; MyFile : file of Byte; MySet : set of 'A' .. 'Z'; MyClass : TMyClass; MyFunc : TMyFun;begin case Self.Tag of 0: Caption := 'Tag 为 0'; else Caption := 'Tag 非 0'; end;end;--------------------------------------------------------------------------------------{ as 关键字 }procedure TForm1.Button1Click(Sender: TObject);begin { Sender 本来是 TObject 类型,现在当作 TButton 类型使用 } (Sender as TButton).Caption := '测试 as 转换'end;---------------------------------------------------------------------------------------{ is 关键字 判断 }procedure TForm1.Button1Click(Sender: TObject);begin if Sender is TForm then ShowMessage('Sender is TForm'); { 显然 Sender 与 TForm 无关 } if Sender is TButton then ShowMessage('Sender is TButton'); { Sender 就是 TButton } if Sender is TCustomButton then ShowMessage('Sender is TCustomButton'); { Sender 继承自 TCustomButton } if Sender is TObject then ShowMessage('Sender is TObject'); { Sender 继承自 TObject }end; |
3、关于 as 的一些使用说明:
as运算符执行选中的类型转换。表示:
|
1
|
object as class |
返回对与object相同的对象的引用,但其类型由类给定。在运行时,对象必须是由类或其子类之一表示的类的实例,或者为nil;否则将引发异常。如果声明的对象类型与类无关——也就是说,如果类型是不同的,并且一个不是另一个的祖先——则会产生编译错误。例如:
|
1
2
3
4
5
|
with Sender as TButton dobegin Caption := '&Ok'; OnClick := OkClick;end; |
运算符优先级规则通常要求as类型转换包含在括号中。例如:
|
1
|
(Sender as TButton).Caption := '&Ok'; //TButton(sender).Caption := '&Ok'; |

浙公网安备 33010602011771号