我正在使用 Delphi XE5 制作一个小的 Delphi 程序。在我的代码中有一个动态布尔数组,我无法更改某些数组元素的值。我尝试在设置长度后初始化数组,但没有帮助。这是代码的一部分:
procedure DoSomething(names: array of string);
var startWithA: array of Boolean;
i: integer;
begin
SetLength(startWithA, Length(names)); // each element is false by default
for i := 0 to Length(names) - 1 do begin
if (names[i].indexOf('A') = 0) then begin
startWithA[i] := true; // the value is not changed after executing this line
end;
end;
end;
Run Code Online (Sandbox Code Playgroud)
你的代码工作得很好。这是证据:
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function StartsWithAIndices(const Names: array of string): TArray<Boolean>;
var
i: Integer;
begin
SetLength(Result, Length(Names));
for i := 0 to high(Result) do begin
if (Names[i].IndexOf('A') = 0) then begin
Result[i] := true;
end;
end;
end;
var
Indices: TArray<Boolean>;
b: Boolean;
begin
Indices := StartsWithAIndices(['Bob', 'Aaron', 'Aardvark', 'Jim']);
for b in Indices do begin
Writeln(BoolToStr(b, True));
end;
Readln;
end.
Run Code Online (Sandbox Code Playgroud)
输出
错误的 真的 真的 错误的
也许您的困惑源于这样一个事实,即您分配给一个局部变量且其值永远不会被读取的数组。如果你从不读取数组值,你怎么能说数组值没有被修改呢?或者也许您启用了优化,并且编译器决定优化掉其值已写入但从未读取的局部变量。
顺便说一句,您的函数可以更简单地编写如下:
function StartsWithAIndices(const Names: array of string): TArray<Boolean>;
var
i: Integer;
begin
SetLength(Result, Length(Names));
for i := 0 to high(Result) do begin
Result[i] := Names[i].StartsWith('A');
end;
end;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3087 次 |
| 最近记录: |