今天写代码发现个bug,是delphi 编译器 核心层面的:

unit ddx.att;

interface

uses System.Generics.Collections, System.Rtti;

type

  xstring = string;

  InstanceName = class(TCustomAttribute)
  private
    Fvalue: array of string;
  public
    constructor Create(AValue:  array of string);
  end;

implementation

constructor InstanceName.Create(AValue:  array of string);
begin
  inherited Create;
  Fvalue := AValue;
end;

新版本,以后 还是 多用 TArray作为 入参吧;

unit ddx.att;

interface

uses System.Generics.Collections, System.Rtti;

type

  xstring = string;

  InstanceName = class(TCustomAttribute)
  private
    Fvalue: TArray<xstring>;
  public
    constructor Create(AValue: TArray<xstring>);
  end;

implementation

constructor InstanceName.Create(AValue: TArray<xstring>);
begin
  inherited Create;
  Fvalue := AValue;
end;

end.

 

又做了一个测试 使用 Tarray和 array of 都可以 很好的 作为参数:

 

在 Delphi 中,array of T 和 TArray<T> 都用于表示动态数组,但它们之间存在一些关键区别,尤其是在类型安全性和使用方式上。

  1. array of T
    • 这是 Delphi 中传统的动态数组声明方式。
    • 它不是类型安全的,因为你可以将一种类型的动态数组赋值给另一种类型的动态数组(尽管这通常是不安全的,并且可能导致运行时错误)。
    • 使用 SetLength 函数来分配和重新分配内存。
    • 在较旧的 Delphi 版本中,这是创建动态数组的唯一方式。
  2. TArray<T>
    • TArray<T> 是 Delphi 引入泛型后提供的一个动态数组类型,其中 T 是数组元素的类型。
    • 它是类型安全的,因为泛型提供了编译时类型检查。这意味着你不能将 TArray<Integer> 赋值给 TArray<String>,除非显式地进行类型转换(这通常是不可能的,因为它们表示完全不同的元素类型)。
    • TArray<T> 通常与泛型集合类一起使用,提供了更好的代码重用和更强的类型安全性。
    • 在内部,TArray<T> 实际上就是一个 array of T,但编译器为其提供了额外的类型检查和可能的优化。
    • 你可以使用 Length 函数来获取数组的长度,并且可以通过直接赋值来调整数组大小(这将自动调用 SetLength)。

使用建议

  • 如果你正在使用较新的 Delphi 版本(尤其是支持泛型的版本),建议使用 TArray<T>,因为它提供了更好的类型安全性和更现代的编程风格。
  • 如果你正在维护较旧的代码库或需要与不支持泛型的库互操作,则可能需要继续使用 array of T

示例

使用 array of T

 
delphi复制代码
 
 
var
 
Ints: array of Integer;
 
begin
 
SetLength(Ints, 5);
 
Ints[0] := 10;
 
end;
 

使用 TArray<T>

 
delphi复制代码
 
 
var
 
Ints: TArray<Integer>;
 
begin
 
Ints := TArray<Integer>.Create(10, 20, 30, 40, 50);
 
// 或者使用动态数组初始化器
 
Ints := [10, 20, 30, 40, 50];
 
end;
 

注意:在上面的 TArray<T> 示例中,我使用了动态数组初始化器,这是 Delphi 的一种语法糖,允许你更简洁地初始化动态数组。然而,这种初始化方式实际上在内部调用了 SetLength 和逐个元素的赋值操作。

posted on 2024-02-03 16:32  del88  阅读(153)  评论(1编辑  收藏  举报