• 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; 清空参数列表一样,这样更安全些。

  • 相关阅读:
    安装XMind如何安装到指定目录
    显示器AVG、DVI、HDMI、DisplayPort、Type-C、雷电接口
    SATA与PCI-E速度对比
    SRAM、DRAM、Flash、DDR有什么区别
    USB3.0与Type-C接口的关系
    一图明白ACHI,SATA之间的关系
    U.2与M.2接口
    遗传算法实例分析
    从零开始写代码-python解深度学习神经网络题目
    基于Yen算法的k最短路径问题的python实现
  • 原文地址:https://www.cnblogs.com/yehuiyan/p/14438361.html
Copyright © 2020-2023  润新知