Abstract error when splitting a string

非 Y 不嫁゛ 提交于 2019-12-11 09:46:15

问题


when using this procedure, i am getting an abstract error (that's all it says). i use this procedure in other projects, this is the first time i've run into it. i'm not sure if it has to do with the syntax of the input string.

procedure SplitString(const Delimiter: Char; Input: string; const Strings: TStrings);
begin
  //Delimits or splits the received string, returns TStrings array
   Assert(Assigned(Strings)) ;
   Strings.Clear;
   Strings.Delimiter := Delimiter;
   Strings.StrictDelimiter := True; //needed otherwise whitespace is used to delimit
   Strings.DelimitedText := Input;
end;

the application calls like this:

      try
        LBOMPartLine := TStrings.Create;
        SplitString(',','C:\DATA\Parts\PART4.PS.0,10,10',LBOMPartLine);
      ...

I've removed some of the debug code that highlighted the fact that the procedure fails, nothing after or before. Can I not use a comma as a separator?


回答1:


The problem is with this line:

LBOMPartLine := TStrings.Create;

TStrings is an abstract class, and you can't create an instance of it. You have to create an instance of a descendant, such as TStringList instead. The documentation clearly says (emphasis added):

Derive a class from TStrings to store and manipulate a list of strings. TStrings contains abstract or, in C++ terminology, pure virtual methods and should not be directly instantiated.

You typically use TStrings as the type of a parameter that a function or procedure receives, so that you can accept any TStrings descendant such as a TStringList, TComboBox.Items', orTMemo.Lines`.

The solution is to create an instance of a descendant:

var
  LBOMPartLine: TStrings; // or more clearly, TStringList
begin
  LBOMPartLine := TStringList.Create;
  try
    SplitString(',','C:\DATA\Parts\PART4.PS.0,10,10',LBOMPartLine);
    // Do whatever else
  finally
    LBOMPartLine.Free;
  end;
end;



回答2:


TStrings is an abstract class, and thats why you're getting abstract error. LBOMPartLine has to be declared as TStringList instead, which is descendant of TStrings class.

Compiler warns you about instantiating a class that has abstract methods - I suggest that you don't ignore warnings and try to write proper code, without them.

Also, class creation should be done outside of try/finally block:

some_class := TSomeClass.Create;
try
  ..
finally
  some_class.Free;
end;


来源:https://stackoverflow.com/questions/18669014/abstract-error-when-splitting-a-string

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