Delphi Win32中的类助手和字符串

时间:2009-09-11 06:28:57

标签: delphi class string operator-overloading helpers

目前的delphi有没有办法实现。

a)具有运算符重载的字符串(作为类)(即。+,=)

b)Class Helper,所以可以添加自定义字符串方法

我收集的字符串是本机类型,因此没有使用类帮助程序 设立班级等。

3 个答案:

答案 0 :(得分:4)

是的,string是一个本机类型,添加了一些特殊的编译器魔法。

我不知道您想要的运算符重载。 +和=已经作为连接和相等运算符工作。

但是我想过自己做类似的事。它可能适用于具有隐式转换器和重载的add和equals运算符的记录类型(在Win32 Delphi中,只有记录可以有运算符重载。这仅在D2006(?2005)中可用。)

我怀疑也可能会有一些性能受损。

语法类似于以下内容:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

   TString = record
    private
      Value : string;
    public
      class operator Add(a, b: TString): TString;
      class operator Implicit(a: Integer): TString;
      class operator Implicit(const s: string): TString;
      class operator Implicit(ts: TString): String;
      function IndexOf(const SubStr : string) : Integer;
    end;


var
  Form1: TForm1;

implementation

class operator TString.Add(a, b : TString) : TString;
begin
  Result.Value := a.Value + b.Value;
end;

class operator TString.Implicit(a: Integer): TString;
begin
  Result.Value := IntToStr(a);
end;

class operator TString.Implicit(ts: TString): String;
begin
  Result := ts.Value;
end;

function TString.IndexOf(const SubStr : string) : Integer;
begin
  Result := Pos(SubStr, Value);
end;

class operator TString.Implicit(const s: string): TString;
begin
  Result.Value := s;
end;


{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  ts : TString;
begin
  ts := '1234';
  ShowMessage(ts);
  ShowMessage(IntToStr(Ts.IndexOf('2')));
end;

end.

显然你也可以拥有“记录助手”,但我自己从未尝试过。

答案 1 :(得分:1)

编写自定义函数/过程不是更好的解决方案吗?

例如

Function StrToBase64(AString): string;
Procedure StrToGridLayout(AString: string; AGrid: TDBGrid);
Function ExtractWord(aString): string;
Function GetStrColumn(aString: string; aCol: integer): string;

如果您想将这些功能/程序归为功能类别中的同一单元,您可以使用以下记录:

TStringConversions = record
  class Function StrToBase64(AString): string;
  class Procedure StrToGridLayout(AString: string; AGrid: TDBGrid);
end;

TStringParsing = record
  class Function ExtractWord(aString): string;
  class Function GetStrColumn(aString: string; aCol: integer): string;
end;

然后,您可以用更清晰的方式在代码中调用它们:

myFirstWord := TStringParsing.ExtractWord('Delphi is a very good tool');

HTH

答案 2 :(得分:1)

您可以在Delphi中使用运算符重载(自Delphi 2006起)仅对不在类上的记录使用,而不是在内置本机类型(如字符串)上使用。

原因是Delphi没有垃圾收集,因此运算符重载仅限于值类型(不在堆上的类型)。

您可以在CodeRage III Replay download page下载我的会话“带有记录,方法和操作员重载的可空类型”的重播。 只需搜索会话名称。

还有page with the download for the session samples and slides

它包含了很多让您前进的示例,包括Delphi 2006编译器中已在Delphi 2007及更高版本中解决的一些问题的描述。

另请参阅此问题:Can I overload operators for my own classes in Delphi?

相关问题