Home > Back-end >  About () function returns an abstract class TStrings is empty
About () function returns an abstract class TStrings is empty

Time:05-10

When operating a function, need to return an abstract class TStringS, the resulting value is empty


Private
{Private declarations}
The Function getList: TStringS;
-- -- -- -- -- --
The Function TForm1. GetList: TStringS;
Var
Aa: TStringList;
I: integer;
STR: string;
The begin
Aa:=TStringList. Create;
Aa. The Add (' ABC '); Aa. The Add (' def '); Aa. The Add (' ghi);
Result:=aa;
FreeAndNil (aa); -- -- -- "here to release object, returns null, if not released, for the right, don't call this object outside release?
end;

Procedure TForm1. Button1Click (Sender: TObject);
Var
Ts: TStringList;
The begin
Ts:=TStringList. Create;
Ts. The Assign (getList);
ShowMessage (ts) Text); -- - " here
FreeAndNil (ts);
end;

CodePudding user response:

Aa:=TStringList. Create; After creation, to like actually exists, but no content of the List
Aa. The Add (' ABC '); Aa. The Add (' def '); Aa. The Add (' ghi); Here is a List added content,
Result:=aa; Here is said to have () function returns aa, but is not to say that there is direct return
FreeAndNil (aa); Here you released to like, the whole of like empty,
The function returns the aa is empty,

So when you getList after, you can only get a nil

Solution, you can use global variables,

CodePudding user response:

You should be the object of the Strings, rather than the object of the Strings back to
Usually, it is recommended to use TStringList, not recommended TStrings

Private
{Private declarations}
Procedure getList (theList: TStrings);
-- -- -- -- -- --
Procedure TForm1. GetList (theList: TStringS);
Var
I: integer;
STR: string;
The begin

TheList. Add (' ABC ');
TheList. Add (' def ');
TheList. Add (' ghi);


end;

Procedure TForm1. Button1Click (Sender: TObject);
Var
Ts: TStringList;
The begin
Ts:=TStringList. Create;
GetList (ts);
ShowMessage (ts) Text); - "here is empty
FreeAndNil (ts);
end;

CodePudding user response:

The Result and aa is a pointer to the same StringList,
Aa to StringList released, the Result to the StringList, of course, also has released,

CodePudding user response:

Result:=aa; Is a pointer assignment, not object assignment,
The solution:
Result:=TStringList. Create;
Result. The Assign (aa);//or Result. Text:=aa. The Text;
  • Related