Delphi:记录构造函数vs工厂函数 [英] Delphi: Record constructor vs factory function
问题描述
那么初始化记录的首选方式是什么?
So what will be the preferred way of initializing records?
使用工厂函数:
TMyRecord = record
valueX: integer;
valueY: integer;
end;
function MyRecord(const AValueX, AValueY: integer): TMyRecord;
begin
result.valueX := AValueX;
result.valueY := AValueY;
end;
var
myrec: TMyRecord;
begin
myrec := MyRecord(1, 2);
end;
或构造函数:
TMyRecord = record
valueX: integer;
valueY: integer;
constructor Create(const AValueX, AValueY: integer);
end;
constructor TMyRecord.Create(const AValueX, AValueY: integer);
begin
self.valueX := AValueX;
self.valueY := AValueY;
end;
var
myrec: TMyRecord;
begin
myrec := TMyRecord.Create(1, 2);
end;
我觉得构造函数更加封装,但是在读取代码时很容易弄错。它使它看起来像一个缺少免费电话的课程。还有更多的是输入...
I feel that the constructor things more encapsulated, but it makes it easy to get confused when reading code. It makes it look like a class that lack a call to free. It's also more to type...
为什么你比较喜欢一个?
Why would you prefer one over the other?
推荐答案
我更喜欢类,但是如果我必须使用记录,我喜欢把它们尽可能地类似于类。所以我使用记录构造函数。
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;
这篇关于Delphi:记录构造函数vs工厂函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!