Is it possible to use two record helpers for the string type?

那年仲夏 提交于 2019-12-30 06:03:48

问题


I created this helper in order to add some more functions to the string type:

type
  AStringHelper = record helper for string
    function Invert: string; overload;
    function InvertMe: string; overload;
  end;

But when I use it in my code, the TStringHelper in System.StrUtils "gets out" and I can't use it's functions.

Is it possible to both of them to coexist?


回答1:


At most one helper can active at any one point in your code. The documentation says this:

You can define and associate multiple helpers with a single type. However, only zero or one helper applies in any specific location in source code. The helper defined in the nearest scope will apply. Class or record helper scope is determined in the normal Delphi fashion (for example, right to left in the unit's uses clause).

Since record helpers do not support inheritance, there's no way to have both the standard helper's and your helper's functionality active at the same time, other than re-implementing the standard helper's functionality.




回答2:


Try to create your own class and helper

TMyString = type string;
TMyStringHelper = record helper for TMyString 
  function Invert: TMyString; 
  function ToString: string;
end;

Use TMyString instead of String.

To use standard String helpers wrap TMyString variable with String() or use ToString method.

var
  S1: TMyString;
  S2: String;
begin
  S1 := ' 123456 ';
  S1.Invert;
  S2 := String(S1).Trim;
  S2 := S1.ToString.Trim;
end;



回答3:


A simple solution to this could be:

type
  TStr = record
  private
    FStr:string;
  public
    function Invert: string; overload;
    function InvertMe: string; overload;
  end;

By using type casting you can access the functions on TStr on a ordinary string variable:

var
  s1,s2:string;
begin
  s1:='123456';
  s2:=TStr(s1).invert;
end;

But of course, then we can ask: Why not just write an ordinary function? :-)

Anyway, I like this class / object / record method syntax better than traditional function/procedure.




回答4:


Another possibility is to use the "Ancestor list" option offered by helpers

Syntaxis:

type
identifierName = class|record helper [(ancestor list)] for TypeIdentifierName
  memberList
end;

And use like this:

Unit1:   
THelperBase = Class helper for TMyClass
Public
  Function SayHello;
end;

Unit2:
Uses Unit1;
THelperChild = Class helper (THelperBase) for TMyClass
Public
  Function SayGoodBye;
end;

And finally, in your code:

Uses Unit2;   

Var MyClass: TMyclass;   

MyClass:= TMyclass.Create;
MyClass.SayHello; //valid
MyClass.SayGoodBye; //valid


来源:https://stackoverflow.com/questions/17899681/is-it-possible-to-use-two-record-helpers-for-the-string-type

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