gpt4 book ai didi

delphi - 使用 TArray 而不是 Array of T 的原因是什么?

转载 作者:行者123 更新时间:2023-12-03 14:33:05 25 4
gpt4 key购买 nike

我正在将旧版 Delphi 应用程序迁移到 Delphi-XE2,我想知道是否有充分的理由替换定义为 Array of MyType 的数组。至TArray<MyType> 。那么问题来了 TArray<T> 的优缺点是什么?用法而不是 MyType 数组?

最佳答案

主要优点是类型身份规则不那么繁重。考虑:

a: array of Integer;
b: array of Integer;

这两个变量不兼容赋值。这么写是编译器错误:

a := b;

另一方面,如果您使用通用语法:

a: TArray<Integer>;
b: TArray<Integer>;

那么这两个变量是赋值兼容的。

当然,你可以写

type
TIntegerArray = array of Integer;

但各方需要就同一类型达成一致。如果所有代码都在您的控制之下,那很好,但是当使用来自各种来源的代码时,通用动态数组的出现会产生巨大的差异。

同样,我想到的另一个优点是您可以轻松使用泛型数组类型作为泛型方法的返回类型。

如果没有通用数组,您就必须声明这种形式的类型:

TArrayOfT = array of T

在你的泛型类中,这相当困惑。如果您在非泛型类中编写泛型方法,则无法进行该声明。通用数组再次解决了这个问题。

TMyClass = class
class function Foo<T>: TArray<T>; static;
end;

这一切都遵循 documentation 中描述的类型兼容性规则。像这样:

Type Compatibility

Two non-instantiated generics are considered assignment compatible only if they are identical or are aliases to a common type.

Two instantiated generics are considered assignment compatible if the base types are identical (or are aliases to a common type) and the type arguments are identical.

关于delphi - 使用 TArray<T> 而不是 Array of T 的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14383093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com