Delphi: Record constructor vs factory function

后端 未结 4 2006
再見小時候
再見小時候 2021-02-12 20:25

So what will be the preferred way of initializing records?

With a \'factory function\':

TMyRecord = record
  valueX: integer;
  valueY: integer;
end;

fu         


        
4条回答
  •  长发绾君心
    2021-02-12 20:45

    I prefer classes, but if I have to use records, I like to treat them as similar as classes as possible. So I use the record constructor.

    But there is an annoying bug with records and units. If a function returns a record (with methods), it produces an internal error if you want to access these methods. You can circumvent this by assigning it to another variable:

    type 
      TMyRec = record
        ..
        procedure X;
      end;
    
    
    function GetRec: TMyRec;
    
    
    
    procedure Test;
    var
      r1, r2 : TMyRec;
    begin
      r1 := GetRec;
      r1.X; // internal error
      r2 := r1;
      r2.X; // No internal error;
    

提交回复
热议问题