使用TArray<T>的原因是什么?而不是 T 数组? [英] What are the reasons to use TArray<T> instead of Array of T?

查看:20
本文介绍了使用TArray<T>的原因是什么?而不是 T 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将旧的 Delphi 应用程序迁移到 Delphi-XE2,我想知道是否有充分的理由将定义为 Array of MyType 的数组替换为 TArray;.所以问题是 TArray 使用而不是 MyType Array 的优缺点是什么?

I'm migrating a legacy Delphi application to Delphi-XE2, and I'm wondering if there's a good reason to replace the arrays defined as Array of MyType to TArray<MyType>. So the question is what are the pros and cons of TArray<T> usage instead of Array of MyType?

推荐答案

主要优点是不那么繁琐的类型标识规则.考虑:

The main advantage is less onerous type identity rules. Consider:

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

这两个变量的赋值不兼容.写成编译器错误:

These two variables are not assignment compatible. It is a compiler error to write:

a := b;

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

On the other hand if you use the generic syntax:

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

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

then these two variables are assignment compatible.

当然可以写

type
  TIntegerArray = array of Integer;

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

But all parties need to agree on the same type. It's fine if all code is in your control, but when using code from a variety of sources, the advent of generic dynamic arrays makes a huge difference.

类似的另一个优点是,您可以轻松地使用泛型数组类型作为泛型方法的返回类型.

The other advantage that springs to mind, in similar vein, is that you can readily use the generic array type as the return type of a generic method.

如果没有泛型数组,您将不得不声明这种形式的类型:

Without the generic array you are compelled to declare a type of this form:

TArrayOfT = array of T

在您的泛型类中,这相当混乱.如果您在非泛型类中编写泛型方法,则无法进行该声明.泛型数组再次解决了这个问题.

in your generic class, which is rather messy. And if you are writing a generic method in a non-generic class, then you've no way to make that declaration. Again the generic array solves the problem.

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

这一切都遵循文档中描述的类型兼容性规则,如下所示:

This all follows on from type compatibility rules described in the documentation like this:

类型兼容性

两个非实例化泛型被认为是赋值仅当它们相同或是某个的别名时才兼容普通类型.

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

两个实例化的泛型被认为是赋值如果基本类型相同(或者是 a 的别名),则兼容公共类型)和类型参数相同.

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.

这篇关于使用TArray&lt;T&gt;的原因是什么?而不是 T 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆