写了个函数把string转换成TStringList,但是报访问冲突,求解
代码如下:
unit Unit1;interfaceuses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;type
TForm1 = class(TForm)
Button1: TButton;
;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;var
Form1: TForm1;
function AnalyseHead(head: string): TStringList;implementation{$R *.dfm}function AnalyseHead(head: string): TStringList; //把分割的string转换成TStringList
var
i: integer;
tempstr: string;
TempList: TStringList;
begin
tempstr := '';
TempList := TStringList.Create;
for i:=1 to length(head) do
if copy(head,i,1) <> '-' then
begin
tempstr := tempstr + copy(head,i,1);
end
else
begin
TempList.Add(tempstr);
tempstr := '';
end;
showmessage(inttostr(TempList.Count));
AnalyseHead := TempList;
TempList.Free;
TempList := nil;
end;procedure TForm1.Button1Click(Sender: TObject);
var
templist: TStringlist;
begin
templist := TStringlist.Create;
templist := AnalyseHead('fsdf-sdfsd-sdfsd-sdf-');
showmessage(templist[0]); //报错
end;end.
代码如下:
unit Unit1;interfaceuses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;type
TForm1 = class(TForm)
Button1: TButton;
;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;var
Form1: TForm1;
function AnalyseHead(head: string): TStringList;implementation{$R *.dfm}function AnalyseHead(head: string): TStringList; //把分割的string转换成TStringList
var
i: integer;
tempstr: string;
TempList: TStringList;
begin
tempstr := '';
TempList := TStringList.Create;
for i:=1 to length(head) do
if copy(head,i,1) <> '-' then
begin
tempstr := tempstr + copy(head,i,1);
end
else
begin
TempList.Add(tempstr);
tempstr := '';
end;
showmessage(inttostr(TempList.Count));
AnalyseHead := TempList;
TempList.Free;
TempList := nil;
end;procedure TForm1.Button1Click(Sender: TObject);
var
templist: TStringlist;
begin
templist := TStringlist.Create;
templist := AnalyseHead('fsdf-sdfsd-sdfsd-sdf-');
showmessage(templist[0]); //报错
end;end.
去掉直接將 TempList 轉成 result
这一句赋值赋的是地址,不拷贝内容!
TempList.free将内容是放掉了!
实在要这样做的话,请用AnalyseHead.Assign(TempList);
这样内容拷贝过去了!