如何将INI部分分配给delphi 7中的记录

Cha*_*les 3 delphi delphi-7

对不起,我不清楚......让我们再试一次

我有一个记录类型:

MyRecord = Record
   Name: string;
   Age: integer;
   Height: integer;
   several more fields....
Run Code Online (Sandbox Code Playgroud)

和一个INI文件:

[PEOPLE]
Name=Maxine
Age=30
maybe one or two other key/value pairs
Run Code Online (Sandbox Code Playgroud)

我想要做的就是使用INI文件中的数据加载记录.

我在TStringList中有来自INI的数据我希望能够遍历TStringList并仅使用TStringList中的键值对分配/更新记录字段.

查尔斯

And*_*and 5

所以你有一个包含内容的INI文件

[PEOPLE]
Name=Maxine
Age=30
Run Code Online (Sandbox Code Playgroud)

并希望将其加载到由...定义的记录中

type
  TMyRecord = record
    Name: string;
    Age: integer;
  end;
Run Code Online (Sandbox Code Playgroud)

?这很容易.只需添加IniFilesuses您的单元的子句,然后执行

var
  MyRecord: TMyRecord;

procedure TForm1.Button1Click(Sender: TObject);
begin
  with TIniFile.Create(FileName) do
    try
      MyRecord.Name := ReadString('PEOPLE', 'Name', '');
      MyRecord.Age := ReadInteger('PEOPLE', 'Age', 0);
    finally
      Free;
    end;
end;
Run Code Online (Sandbox Code Playgroud)

当然,MyRecord变量不必是全局变量.它也可以是局部变量或类中的字段.但这完全取决于你的确切情况.

一个简单的概括

一个稍微有趣的情况是你的INI文件包含几个人,比如

[PERSON1]
Name=Andreas
Age=23

[PERSON2]
Name=David
Age=40

[PERSON3]
Name=Marjan
Age=49

...
Run Code Online (Sandbox Code Playgroud)

并且您想将其加载到TMyRecord记录数组中,然后就可以了

var
  Records: array of TMyRecord;

procedure TForm4.FormCreate(Sender: TObject);
var
  Sections: TStringList;
  i: TIniFile;
begin
  with TIniFile.Create(FileName) do
    try
      Sections := TStringList.Create;
      try
        ReadSections(Sections);
        SetLength(Records, Sections.Count);
        for i := 0 to Sections.Count - 1 do
        begin
          Records[i].Name := ReadString(Sections[i], 'Name', '');
          Records[i].Age := ReadInteger(Sections[i], 'Age', 0);
        end;
      finally
        Sections.Free;
      end;

    finally
      Free;
    end;
end;
Run Code Online (Sandbox Code Playgroud)

  • @Andreas PS我喜欢你的示例数据!! (4认同)
  • @David:你不需要说出来 - 我知道.问题是我不知道"TMemIniFile"是否在Delphi 7中可用,这是OP使用的版本. (3认同)
  • @andreas哇,先发制人评论吧!在D7上TMemIniFile很好,在D6上确实存在,甚至更早我打赌. (2认同)