向通用TArray类添加非类函数 [英] Adding non class functions to generic TArray class
问题描述
在 System.Generics.Collections
中, TArray
类型仅具有类函数.
In System.Generics.Collections
, the TArray
type has class functions only.
例如:
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;
推荐答案
您可以为非通用动态数组或完全专用的通用动态数组定义帮助程序.例如,您可以编写:
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.
所以你可以写
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.
这篇关于向通用TArray类添加非类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!