开发者

Default boolean value in a array of record - Delphi

开发者 https://www.devze.com 2023-01-01 21:03 出处:网络
I am helping out my company with some old delphi 7 code. There is a record declared at the start that is used throughout to store all the data we want outputted.

I am helping out my company with some old delphi 7 code.

There is a record declared at the start that is used throughout to store all the data we want outputted.

type

TOutput_Type = record

result: String;

resultoffset: String;

selected: boolean;

resultcategory: integer;

end;

and then an array of this is declared

Output: array of TOutput_Typ开发者_Go百科e;

The length is set at the start to a large value, as actual length is unknown.

This array is used all over the place, but unfortunately the value selected is not always set when used.

My problem is I am adding in a summary of the data, but because selected is not set, delphi seems to give it a random true or false status.

Is there a way of setting all instances of selected as true at the start? Seems like a simple enough thing to do, but I'm not a delphi programmer so am unsure if its possible? I know I can go through and add in selected := true every time a new record is made, but I'd like to do it cleanly at the start if possible....

Thanks in advance


After calling SetLengt for Output variable you must first initiate the new record parts (because new allocated memory isn't defined) in for loop. Something like:

OldLength := Length(Output);
SetLength(Output, NewLength);
for n := OldLength to NewLength -1 do 
  Output[n].selected := True;


Records, unlike objects, aren't initialized upon creation, so you need to initialize them yourself. Since you're on Delphi 7, you can't use records with methods, so what I'd do is make an initialization function, something like this:

type
  TOutputArray: array of TOutput_Type; 

function CreateOutputArray(length: integer): TOutputArray;
var
  i: integer;
begin
  SetLength(result, MyArbitraryItemCount);
  FillChar(result[0], Length(Output)*SizeOf(TOutput_Type), 0);
  for i := 0 to high(result) do
    result[i].selected := true;
end;


I'd go for the factory method like in the question dcp linked to. Parameterless constructors aren't allowed for records, so you would always have to specify some parameters, which might be annoying if you don't really need them.

If this is all about initializing the content of the large array once at the start you could also use this:

SetLength(Output, MyArbitraryItemCount);
FillChar(Output[0], Length(Output)*SizeOf(TOutput_Type), 1);

Then everything is 1. Including selected :) Of course you could also use a for-loop...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号