[fpc-devel] Re: Converting records back and forth. (Forward declarations for records needed ?!?)
Skybuck Flying
skybuck2000 at hotmail.com
Mon Sep 19 12:32:21 CEST 2011
There appears to be a solution in Delphi for this:
It's called "record helpers":
Demonstration program:
// *** Begin of Test Program ***
program TestProgram;
{$APPTYPE CONSOLE}
{
Test circular records problem and solutions.
version 0.01 created on 19 september 2011 by Skybuck Flying
The solution below uses a "record helper" which seems to solve it nicely
and now I can write the code the way I want to...
Not sure if it compiles in free pascal, but it does compile in Delphi XE at
least ;)
(Perhaps another solution could be to use type casting, but that would not
solve
the circular problem, so not going to test that)
}
uses
SysUtils;
type
TrecordB = record
private
mData : double;
public
property Data : double read mData write mData;
end;
TrecordA = record
private
mData : integer;
public
property Data : integer read mData write mData;
function ToRecordB : TrecordB;
end;
// solution: record helper
TrecordBhelper = record helper for TrecordB
private
// mData : double;
public
// property Data : double read mData write mData; // must be in TrecordB
apperently ?!?
function ToRecordA : TrecordA;
end;
function TrecordA.ToRecordB : TrecordB;
begin
result.mData := mData;
end;
function TrecordBhelper.ToRecordA : TrecordA;
begin
result.mData := Round(mData);
end;
procedure Main;
var
vRecordA : TrecordA;
vRecordB : TrecordB;
begin
writeln('program started');
vRecordA.mData := 555;
vRecordB.mData := 666.666;
writeln( 'vRecordA.mData: ', vRecordA.mData );
writeln( 'vRecordB.mData: ', vRecordB.mData );
writeln( 'vRecordA.ToRecordB.mData: ', vRecordA.ToRecordB.mData );
writeln( 'vRecordB.ToRecordA.mData: ', vRecordB.ToRecordA.mData );
writeln('program finished');
end;
begin
try
Main;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
ReadLn;
end.
// *** End of Test Program ***
Bye,
Skybuck.
More information about the fpc-devel
mailing list