Adding non class functions to generic TArray class

和自甴很熟 提交于 2021-01-28 20:35:59

问题


In System.Generics.Collections, the TArray type has class functions only.

For example:

class procedure Sort<T>(var Values: array of T); overload; static;

This implies the only accepted syntax is the following:

var
  Arr : TArray<integer>;
begin
  SetLength(Arr, 2);
  Arr[0] := 5;
  Arr[1] := 3;

  TArray.Sort<integer>(Arr);
end;

I would like to define an object's function in order to sort the values of the generic array using the following syntax:

var
  Arr : TArray<integer>;
begin
  SetLength(Arr, 2);
  Arr[0] := 5;
  Arr[1] := 3;

  Arr.Sort();
end;

回答1:


You can define helpers for non-generic dynamic arrays, or for fully specialized generic dynamic arrays. For instance, you can write:

type
  TMyArray1 = array of Integer;
  TMyArray2 = TArray<Integer>;

  TMyArrayHelper1 = record helper for TMyArray1
  end;
  TMyArrayHelper2 = record helper for TMyArray2
  end;
  TMyArrayHelper3 = record helper for TArray<Integer>
  end;

This allows you to add methods to the scope of such arrays.

So you can write

type
  TIntegerArrayHelper = record helper for TArray<Integer>
    procedure Sort;
  end;

procedure TIntegerArrayHelper.Sort;
begin
  TArray.Sort<Integer>(Self);
end;

However, what you cannot do is write:

  TMyArrayHelper<T> = record helper for TArray<T>
  end;

The compiler simply does not support generic helpers.

None of this is worthwhile in my view, just call:

TArray.Sort<T>()

directly. Adding a record helper, and having to make one for each element type that you wish to support, seems to me like a cost that does not justify the return.



来源:https://stackoverflow.com/questions/60631796/adding-non-class-functions-to-generic-tarray-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!