有没有办法用目前的delphi来实现。
a) 具有运算符重载(即 +、=)的字符串(作为类)
b) 类帮助器,以便可以添加自定义字符串方法
我收集字符串是 native 类型,因此如果没有,类助手将无法工作 设置类(class)等。
最佳答案
是的,字符串是一种 native 类型,添加了一些特殊的编译器魔法。
我不知道您想要什么运算符重载。 + 和 = 已经用作连接和相等运算符。
但是我也想过自己做一些类似的事情。它可能适用于具有隐式转换器和重载的 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.
显然你也可以拥有“记录助手”,但我自己从未尝试过。
关于delphi - Delphi Win32 中的类帮助器和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1409294/