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

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

问题描述

我正在将一个旧的Delphi应用程序迁移到Delphi-XE2,我想知道是否有一个很好的理由将定义为 MyType 的数组替换为 TArray< MyType> 。所以问题是 TArray< T> 使用而不是MyType数组的优缺点是什么?

解决方案

主要优点是较少繁琐的类型身份规则。考虑:

  a:整数数组; 
b:整数数组;

这两个变量不兼容。写一个编译器错误:

  a:= b; 

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

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

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



当然可以写

  type 
TIntegerArray = Integer数组;

但是所有各方都需要同意类型。如果所有的代码都在你的控制之下,这是很好的,但是当使用各种来源的代码时,通用的动态数组的出现就会有很大的区别。



要想起来,你可以使用通用数组类型作为通用方法的返回类型。



没有通用数组,你被迫声明一种这种形式:

  TArrayOfT = T 
的数组

在你的泛型类,这是相当凌乱。而且,如果您在非泛型类中编写通用方法,那么您无法做出该声明。通用数组也解决了这个问题。

  TMyClass = class 
class function Foo< T> ;:TArray< T> ;静态的;
结束

这一切都遵循


类型兼容性

/ strong>



两个未实例化的泛型被视为赋值
兼容,只有当它们相同或者是
常用类型的别名时。 p>

如果基本类型相同(或者是
常用类型的别名),并且类型参数是相同的,则两个实例化泛型被视为赋值
兼容。



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.

Sure, you can write

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:

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.

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

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