Delphi:记录构造函数vs工厂函数

编程入门 行业动态 更新时间:2024-10-24 02:03:03
本文介绍了Delphi:记录构造函数vs工厂函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

那么初始化记录的首选方式是什么?

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工厂函数

本文发布于:2023-10-16 11:55:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497487.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   工厂   Delphi

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!