type 关键字在类型定义中的实际含义是什么?
What does `type` keyword actually means when used in a type definition?
我最近阅读了 VCL 源代码的一些行并找到了 TCaption
类型的定义:
TCaption = type string;
我一直以为它只是string
类型的别名,我以为它的定义如下:
TCaption = string;
所以,我搜索了 documentation 关于 type
关键字,我找到了这个:
type Name = Existing type
Refers to an existing type, such as string by a new Name.
type Name = type Existing type
This has the same effect as above, but ensures that at run time, variables of this type are identified by
their new type name, rather than the existing type name.
看完还是一头雾水,不明白什么"...保证在运行的时候,这个类型的变量用他们的新类型来标识名称..." 实际上意味着.
有人能解释一下吗?
类型声明如
TCaption = type string;
创建具有不同 RTTI 信息的新类型。如果需要 string
类型,它也不能用作函数的 var
参数。
新的 RTTI 信息“......确保在 运行 时间,这种类型的变量由它们的新类型名称标识......”。因此,如果您尝试获取 TCaptionSame = string;
实例的类型名称,您将获得 string
,而对于 TCaption
类型变量,您将获得 TCaption
要获得更准确的信息,最好参考official help
考虑以下代码,注意过程 Check()
有一个 var
参数:
type
Ta = string; // type alias
Tb = type string; // compatible but distinct new type
procedure Check(var s: string);
begin
ShowMessage(s);
end;
procedure TMain.Button2Click(Sender: TObject);
var
a: Ta;
b: Tb;
begin
a := 'string of type Ta,';
b := 'string of type Tb.';
Check(a);
Check(b);
end;
Check(b)
导致编译器错误:
E2033 实际和形式 var 参数的类型必须相同
在上面,类型 Tb
与 string
兼容,因为您可以 f.前任。分配 a := b
,但它的不同之处在于 type identifier
(在引擎盖下)具有不同的值,因此不被接受为 Check(var s: string)
.
的参数
我最近阅读了 VCL 源代码的一些行并找到了 TCaption
类型的定义:
TCaption = type string;
我一直以为它只是string
类型的别名,我以为它的定义如下:
TCaption = string;
所以,我搜索了 documentation 关于 type
关键字,我找到了这个:
type Name = Existing type
Refers to an existing type, such as string by a new Name.type Name = type Existing type
This has the same effect as above, but ensures that at run time, variables of this type are identified by their new type name, rather than the existing type name.
看完还是一头雾水,不明白什么"...保证在运行的时候,这个类型的变量用他们的新类型来标识名称..." 实际上意味着.
有人能解释一下吗?
类型声明如
TCaption = type string;
创建具有不同 RTTI 信息的新类型。如果需要 string
类型,它也不能用作函数的 var
参数。
新的 RTTI 信息“......确保在 运行 时间,这种类型的变量由它们的新类型名称标识......”。因此,如果您尝试获取 TCaptionSame = string;
实例的类型名称,您将获得 string
,而对于 TCaption
类型变量,您将获得 TCaption
要获得更准确的信息,最好参考official help
考虑以下代码,注意过程 Check()
有一个 var
参数:
type
Ta = string; // type alias
Tb = type string; // compatible but distinct new type
procedure Check(var s: string);
begin
ShowMessage(s);
end;
procedure TMain.Button2Click(Sender: TObject);
var
a: Ta;
b: Tb;
begin
a := 'string of type Ta,';
b := 'string of type Tb.';
Check(a);
Check(b);
end;
Check(b)
导致编译器错误:
E2033 实际和形式 var 参数的类型必须相同
在上面,类型 Tb
与 string
兼容,因为您可以 f.前任。分配 a := b
,但它的不同之处在于 type identifier
(在引擎盖下)具有不同的值,因此不被接受为 Check(var s: string)
.