阅读 89

delphi中使用array结构体最好的例子

转自https://blog.csdn.net/qq_26657857/article/details/88733320 在开发中,能用结构体尽量不用类,因为结构体的存储机制是“栈”,这就意味着自动释放内存。但是在使用过程中也要注意以下几点:1.用完清空 2.用多少申请多少 下面用具体实例说明: unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TScore=record course:string; score:real; end; TPerson=record Name:string; ScoreList:array of TScore; end; TForm1 = class(TForm) Memo1: TMemo; Button1: TButton; Button2: TButton; Button3: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure showPeople(p:TPerson); end; var Form1: TForm1; implementation {$R *.dfm} var p:TPerson; procedure TForm1.Button1Click(Sender: TObject); begin p.Name:=‘张三‘; setlength(p.ScoreList,3);//有3门课程 p.ScoreList[0].course:=‘语文‘; p.ScoreList[0].score:=98.5; p.ScoreList[1].course:=‘数学‘; p.ScoreList[1].score:=95; p.ScoreList[2].course:=‘英语‘; p.ScoreList[2].score:=87; showPeople(p); end; procedure TForm1.Button2Click(Sender: TObject); begin p.Name:=‘李四‘; setlength(p.ScoreList,3);//有3门课程 p.ScoreList[0].course:=‘语文‘; p.ScoreList[0].score:=78.5; p.ScoreList[1].course:=‘数学‘; p.ScoreList[1].score:=70; p.ScoreList[2].course:=‘英语‘; p.ScoreList[2].score:=60; showPeople(p); end; procedure TForm1.Button3Click(Sender: TObject); begin p.Name:=‘黄晓娜‘; FillChar(p.ScoreList,sizeof(p.ScoreList),0); //这里清空缓存数据,生成 p.ScoreList=() setlength(p.ScoreList,2); //这种方法得到:p.ScoreList=((course=‘数学‘;score=78.5),(course=‘语文‘;score=70)) 采用截断模式 p.ScoreList[0].course:=‘语文‘; p.ScoreList[0].score:=88.5; p.ScoreList[1].course:=‘数学‘; p.ScoreList[1].score:=90; showPeople(p); end; procedure TForm1.showPeople(p: TPerson); var i:integer; begin memo1.Lines.Add(p.Name); for I := Low(p.ScoreList) to High(p.ScoreList) do begin memo1.Lines.Add(format(‘%s:%.2f‘,[p.ScoreList[i].course,p.ScoreList[i].score])); end; end; end. 说明: 综合上面的问题,如果采用setLength()方法来设置数组,容易因为缓存之前的数据未被更新而产生错误数据,最好使用fillChar() 方法进行清空后再申请。好比在使用FDStoreProcedure fdSp 实例对像时,使用前要 fdSp.Close; fdSp.Parameters.clear; 清空参数列表一样,这样更安全些。

原文:https://www.cnblogs.com/yehuiyan/p/14438361.html

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐