How to set default value to record in delphi

a 夏天 提交于 2019-12-12 20:22:52

问题


I am using RAD XE7. In my Delphi application I want to set default values for fields of Records.

I tried following code, but it does not compile, I know it is wrong. I there any another way?

 TDtcData = record
    TableFormat     : TExtTableFormat = fmNoExtendedData;
    DTC             : integer = 0;
    Description     : string = 'Dummy';
    Status          : TDtcStatus;    
    OccurenceCnt    : integer =20;
    FirstDTCSnapShot: integer;
    LastDTCSnapShot: integer;
  end; 

回答1:


If you want to define a partially initialized record, just declare a constant record, but omit those parameters not needing default values:

Type
  TDtcData = record
  TableFormat     : TExtTableFormat;
  DTC             : integer;
  Description     : string;
  Status          : TDtcStatus;
  OccurenceCnt    : integer;
  FirstDTCSnapShot: integer;
  LastDTCSnapShot: integer;
end;

Const
  cDefaultDtcData : TDtcData = 
    (TableFormat : fmNoExtendedData; 
     DTC : 0; 
     Description : 'Dummy'; 
     OccurenceCnt : 20);

var
  someDtcData : TDtcData;
begin
  ...
  someDtcData := cDefaultDtcData;
  ...
end;



回答2:


With the addition of 'class like' record types in Delphi, you could solve this by using a class function.

Define class function CreateNew: TDtcData; static; for your record.

The implementation sets the default values for the resulting record:

class function TDtcData.CreateNew: TDtcData;
begin
 Result.TableFormat := fmNoExtendedData;
 Result.DTC := 0;
 Result.Description :=  'Dummy';
 Result.OccurenceCnt := 20;
end;

Using this to get a record with the default values like this:

var
  AData: TDtcData;
begin
  AData := TDtcData.CreateNew;;
end.


来源:https://stackoverflow.com/questions/46763864/how-to-set-default-value-to-record-in-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!