How do i return an object from a function in Delphi without causing Access Violation?

后端 未结 10 1234
被撕碎了的回忆
被撕碎了的回忆 2021-02-13 14:54

I have a delphi function that returns a TStringList, but when I return a value and try to use it I get a Access Violation Error i.e

myStringList := FuncStringLis         


        
10条回答
  •  清歌不尽
    2021-02-13 15:24

    Either as Out variable.

    function GetList(Parameter1: string; out ResultList: TStringList): boolean;
    begin
      // either
      if not Assigned(ResultList) then
        raise Exception.Create('Out variable is not declared.');
      // or
      Result := False;
      if not Assigned(ResultList) then
        Exit;
      ResultList.Clear;
      ResultList.Add('Line1');
      ResultList.Add('Line2');
      //...
      Result := True;
    end;
    

    Or as string.

    function GetList(Parameter1: string): string;
    var
      slList: TStringList;
    begin
      slList := TStringList.Create;
      try
        slList.Clear;
        slList.Add('Line1');
        slList.Add('Line2');
        //...
        Result := slList.Text;
      finally
        slList.Free;
      end;
    end;
    

    .

    procedure Main;
    var
      slList: TStringList;
    begin
      slList := TStringList.Create;
      try
        // either
        GetList(Parameter1, slList);
        // or
        slList.Text := GetList(Parameter1);
        // process slList...
      finally
        slList.Free;
      end;
    end;
    

提交回复
热议问题