How to declare a fixed value in a record?

I would like to know how to declare a record that has some fixed values. I need to send data using this template: Byte($FF)-Byte(0..250)-Byte(0..250) . I use record for this, and I would like the first value to be constant, so that it cannot be corrupted. For instance:

 TPacket = record InitByte: byte; // =255, constant FirstVal, SecondVal: byte; end; 
+6
source share
4 answers

You cannot rely on a constructor because, contrary to classes, records are not required for use, the default constructor without parameters is used implicitly.

But you can use a constant field:

 type TPacket = record type TBytish = 0..250; const InitByte : Byte = 255; var FirstVal, SecondVal: TBytish; end; 

Then use this as a regular record, except that you do not (and cannot) change the InitByte field.
FillChar maintains a constant field and behaves as expected.

 procedure TForm2.FormCreate(Sender: TObject); var r: TPacket; begin FillChar(r, SizeOf(r), #0); ShowMessage(Format('InitByte = %d, FirstVal = %d, SecondVal = %d', [r.InitByte, r.FirstVal,r.SecondVal])); // r.InitByte := 42; // not allowed by compiler // r.FirstVal := 251; // not allowed by compiler r.FirstVal := 1; r.SecondVal := 2; ShowMessage(Format('InitByte = %d, FirstVal = %d, SecondVal = %d', [r.InitByte, r.FirstVal,r.SecondVal])); end; 

Updated to include a range of nested type 0..250

+12
source

Modern versions of Delphi allow you to use recording methods. Although you cannot prevent someone from changing the field, you can at least initialize it correctly:

 type TPacket = record InitByte: byte; // =255, constant FirstVal, SecondVal: byte; constructor Create(val1, val2 : byte); end; constructor TPacket.Create(val1, val2: byte); begin InitByte := 255; FirstVal := val1; SecondVal := val2; end; 
+2
source

Given the fact that records can now have properties, you can define a record as:

 TMixedFixed = record strict private FFixed: byte; FVariable1: byte; FVariable2: byte; public property Fixed read FFixed; property Variable read FVariable write FVariable; constructor Create(Var1, Var2: byte); end; constructor TMixedFixed.create(Var1, Var2: byte); begin FFixed:= 255; FVariable1:= Var1; FVariable2:= Var2; end; 

Given that real variables are strict quotients, you should not touch them without much magic. You will need to use the constructor to initialize the "fixed" values.

0
source

This is the easiest way:

 type TPacket = record InitByte: byte; // =255, constant FirstVal, SecondVal: byte; end; var Packet : TPacket = (InitByte: 255); const Packet1 : TPacket = (InitByte: 255); 
0
source

Source: https://habr.com/ru/post/910839/


All Articles