数组类型可以有方法吗? [英] Can array types have methods?

查看:48
本文介绍了数组类型可以有方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了一个动态数组类型,如下所示:

I have defined a dynamic array type as follows:

TMyIntegerArray = array of integer:

我想使用 IndexOf 函数,就像它是 TObject 的后代一样:

I would like to use an IndexOf function as I would do if it were a TObject's descendant:

var
  MyArray : TMyIntegerArray;
  i : integer:
begin
  //...
  i := MyArray.IndexOf(10);
  //...
end;

目前,我找到的唯一解决方案是编写一个接受数组和目标值作为参数的函数:

At the moment, the only solution I've found is to write a function who accepts the array and the target value as parameters:

function IndexOf(AArray : TMyIntegerArray; ATargetValue : integer; AOffset : integer = 0);
begin
  Result := AOffset;
  while(Result < Length(AArray)) do
  begin
    if(AArray[Result] = ATargetValue)
    then Exit;
    Result := Result + 1;
  end;
  Result := -1;
end;

TMyIntegerArray 类型是否可以具有 IndexOf 之类的功能?

Can TMyIntegerArray type have a function like IndexOf?

其他信息:

当前,我正在使用Delphi2007,但我也想知道是否有任何方法可以在较新的Delphi版本中向数组类型添加方法.

Currently, I'm using Delphi2007 but I'm also interested in knowing if there's any way to add methods to array types in newer Delphi's versions.

推荐答案

在较新版本的Delphi(XE3 +)中,可以使用 record helpers 来实现数组类型的方法:

In newer versions of Delphi (XE3+), it is possible to implement methods to array types with record helpers:

program ProjectTest;

{$APPTYPE CONSOLE}

Type
  TMyArray = array of integer;

  TMyArrayHelper = record helper for TMyArray
    procedure Print;
    function IndexOf(ATargetValue : integer; AOffset : integer = 0): Integer;
  end;

procedure TMyArrayHelper.Print;
var
  i: Integer;
begin
  for i in Self do WriteLn(i);  // Use Self for variable reference
end;

function TMyArrayHelper.IndexOf(ATargetValue : integer; AOffset : integer = 0): Integer;
begin
  Result := AOffset;
  while(Result < Length(Self)) do
  begin
    if(Self[Result] = ATargetValue)
    then Exit;
    Result := Result + 1;
  end;
  Result := -1;
end;

var
  myArr : TMyArray;
begin
  myArr := [0,1,2];  // A neat way to populate a dynamic array (XE7+)
  myArr.Print;
  WriteLn(myArr.IndexOf(2));

  ReadLn;
end.


注意:您可以跳过 TMyArray 类型声明,并使用 TArray< Integer> 获得更宽松的类型解析.与记录助手一样,一种类型只能附加一个助手(而将要使用的是范围最接近的一个).


Note: You can skip the TMyArray type declaration and use TArray<Integer> for a more relaxed type resolution. As always with record helpers, there can be only one helper attached to a type (and the one that will be used is the one nearest in scope).

这种类型的帮助程序称为内部类型帮助程序,编译器在其中放置了一个类型周围的隐式记录结构.

This type of helper is called an intrinsic type helper, where the compiler puts an implicit record structure around the type.

这篇关于数组类型可以有方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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