gpt4 book ai didi

arrays - 从函数返回动态数组

转载 作者:行者123 更新时间:2023-12-03 15:30:52 25 4
gpt4 key购买 nike

我正在使用 Delphi 7。

这是我的基类。函数 load_for_edit() 应该返回一个字符串数组,听起来就像这样。问题不是特别在这里,而是更进一步。

    ...

type
TStringArray = array of string;

...

function load_for_edit(): TStringArray;

...

numberOfFields: integer;

...

function TBaseForm.load_for_edit(): TStringArray;
var
query: TADOQuery;
i: integer;
begin
query := TADOQuery.Create(self);
query.Connection := DataModule1.ADOConnection;
query.SQL.Add('CALL get_' + self.table_name + '_id(' + self.id + ')');
query.Open;

numberOfFields := query.Fields.Count;
SetLength(result, query.Fields.Count);
for i := 0 to query.Fields.Count - 1 do
result[i] := query.Fields[i].Value.AsString;
end;

下一个类是基类的后代,它尝试从基类的 load_for_edit() 函数接收数组。

    ...

type
TStringArray = array of string;

...

procedure TPublisherEditForm.FormShow(Sender: TObject);
var
rec: TStringArray;
begin
inherited;
SetLength(rec, self.numberOfFields);
rec := load_for_edit(); // Compilation stops here
end;

但是,应用程序无法编译。 Delphi 吐出此错误消息:

Incompatible types

因此,这意味着函数 load_for_edit() 返回的数据类型与变量 rec 的数据类型不同,如下所示:从它们各自的类型声明部分来看,它们的声明是完全相同的。我不知道这里发生了什么以及该怎么办。请帮我想出一个解决方案。

最佳答案

您有两个单独的 TStringArray 声明(每个单元一个),并且它们不相同。 (事实上​​,它们位于两个独立的单元中,这使得它们有所不同。UnitA.TStringArrayUnitB.TStringArray 不同,即使它们都声明为类型 TStringArray = 字符串数组;。)

您需要使用单一类型声明:

unit
BaseFormUnit;

interface

uses
...
type
TStringArray: array of string;

TBaseForm = class(...)
numberOfFields: Integer;
function load_for_edit: TStringArray;
end;

implementation

// Not sure here. It looks like you should use a try..finally to
// free the query after loading, but if you need to use it later
// to save the edits you should create it in the TBaseForm constructor
// and free it in the TBaseForm destructor instead, which means it
// should also be a field of the class declaration above.
function TBaseForm.load_for_edit(): TStringArray;
var
query: TADOQuery;
i: integer;
begin
query := TADOQuery.Create(self);
query.Connection := DataModule1.ADOConnection;
query.SQL.Add('CALL get_' + self.table_name + '_id(' + self.id + ')');
query.Open;

numberOfFields := query.Fields.Count;
SetLength(result, numberOfFields);
for i := 0 to numberOfFields - 1 do
Result[i] := query.Fields[i].Value.AsString;
end;
...
end.

现在您的后代类可以访问它:

unit
PublisherEditFormUnit;

interface

uses
... // Usual Forms, Windows, etc.
BaseFormUnit;

type
TPublisherEditForm = class(TBaseForm)
...
procedure FormShow(Sender: TObject);
end;

implementation

procedure TPublisherEditForm.FormShow(Sender: TObject);
var
rec: TStringArray;
begin
// No need to call SetLength - the base class does.
rec := load_for_edit(); // Compilation stops here
end;
...
end.

关于arrays - 从函数返回动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15982980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com