【问题标题】:Why does TJSONObject.AddPair results Self?为什么 TJSONObject.AddPair 结果 Self?
【发布时间】:2021-03-05 09:09:43
【问题描述】:

我注意到TJSONObject.AddPair 函数的结果是Self 而不是新创建的对象:

例如,在System.JSON 单元中我看到以下代码:

function TJSONObject.AddPair(const Str: string; const Val: string): TJSONObject;
begin
  if (not Str.IsEmpty) and (not Val.IsEmpty) then
    AddPair(TJSONPair.Create(Str, Val));
  Result := Self;
end;

我期待这样的事情:

function TJSONObject.AddPair(const Str: string; const Val: string): TJSONObject;
begin
  if (not Str.IsEmpty) and (not Val.IsEmpty) then
    Result := AddPair(TJSONPair.Create(Str, Val));
  else 
    Result := nil;
end;

我觉得这很不寻常,是 Delphi XE7 的错误还是他们这样做的任何技术/实际原因?

【问题讨论】:

  • 你在当前对象上是正常的,通过总结给当前对象添加对的便捷方法确认。否则,你可以使用TJSONPair.Create

标签: json delphi delphi-xe7


【解决方案1】:

返回Self 是一种常见的编码模式,称为fluent interface

它允许您继续调用同一个对象,创建方法链,而无需为每次调用引用对象变量。这使得代码更具可读性,另一方面更难调试。

var
  Obj: TJSONObject;
begin
  Obj := TJSONObject.Create
    .AddPair('first', 'abc')
    .AddPair('second', '123')
    .AddPair('third', 'aaa');
 ...
end;

相当于

var
  Obj: TJSONObject;
begin
  Obj := TJSONObject.Create;
  Obj.AddPair('first', 'abc');
  Obj.AddPair('second', '123');
  Obj.AddPair('third', 'aaa');
 ...
end;

生成的 JSON 对象将如下所示:

{
  "first": "abc",
  "second": "123",
  "third": "aaa"
}

这种编码风格在具有自动内存管理的语言中更为普遍,因为您不需要引入中间变量。

例如,如果您需要 JSON 字符串,您将使用以下构造:

var
  s: string;
begin
  s := TJSONObject.Create
    .AddPair('first', 'abc')
    .AddPair('second', '123')
    .AddPair('third', 'aaa')
    .Format(2);
 ...
end;

上述代码在 Delphi 中的问题在于它会造成内存泄漏,因为您无法释放中间对象。因此,将 fluent interface 模式与引用计数类结合使用更为常见,其中自动内存管理将处理任何中间对象实例的释放。

【讨论】:

  • 就我个人而言,我喜欢流畅的界面,并且在 Delphi 的高级记录中经常使用它们。
  • @AndreasRejbrand 我也爱他们。但是,我使用的是引用计数类。每种方法都有优点和缺点。
猜你喜欢
  • 2017-01-20
  • 2014-08-02
  • 2023-03-08
  • 2012-08-03
  • 1970-01-01
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多