Forum > Beginners
How extend existing class like TStringHelper?
ssawgift:
I could not find any docs on writing code like TStringHelper, i.e. you can call the helper functions as if they are native to the string class. Need some examples.
Thaddy:
Easy.
--- Code: Pascal [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---{$H+}{$mode objfpc}{$modeswitch typehelpers}uses sysutils;type ThwHelper = type helper for AnsiString function Say:ansistring; end; function ThwHelper.Say:ansistring; begin result := 'Hello, World'; end; var a:ansistring;begin writeln( a.say);end.
And https://wiki.freepascal.org/Helper_types#Type_Helper resp. https://www.freepascal.org/docs-html/ref/refch10.html
Reading manuals makes things understandable...
paweld:
https://wiki.freepascal.org/Helper_types#Type_Helper
Thaddy:
--- Quote from: paweld on November 27, 2022, 07:27:51 am ---https://wiki.freepascal.org/Helper_types#Type_Helper
--- End quote ---
Yes, but you should also refer to the official documentation. The wiki is not always the best resource, and not official, although it comes up first in search results. "thanks" but no thanks to Google. Always read the manual.
ssawgift:
Not sure what I have done wrong. I added the following unit to my project and it seems to break existing TStringHelper. I get many errors on existing code that uses TStringHelper functions.
--- Code: Pascal [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---unit Helpers; {$mode ObjFPC}{$H+}{$modeswitch typehelpers} interface uses Classes, SysUtils; { Declaration }type // String helpers MyStringHelper = type helper for AnsiString function IsArg: boolean; end; implementation function MyStringHelper.IsArg: boolean;begin Result := (Length(self) >= 2) and ((self[1] = '/') or (self[1] = '-'));end; end.
Navigation
[0] Message Index
[#] Next page