我想知道如何声明一个具有一些固定值的记录.我需要使用这种模式发送数据:Byte($FF)-Byte(0..250)-Byte(0..250).我正在使用record它,我想让它的第一个值保持不变,这样就不会搞砸了.如:
TPacket = record
InitByte: byte; // =255, constant
FirstVal,
SecondVal: byte;
end;
Run Code Online (Sandbox Code Playgroud)
Fra*_*ois 13
您不能依赖构造函数,因为与Classes相反,Records不需要使用它们,隐式使用默认的无参数构造函数.
但是你可以使用常量字段:
type
TPacket = record
type
TBytish = 0..250;
const
InitByte : Byte = 255;
var
FirstVal,
SecondVal: TBytish;
end;
Run Code Online (Sandbox Code Playgroud)
然后将其用作常规记录,除了您没有(并且不能)更改InitByte字段.
FillChar保留常量字段并按预期运行.
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;
Run Code Online (Sandbox Code Playgroud)
已更新,包括嵌套类型范围0..250