加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 为什么不在返回对象时直接使用Result变量?

发布时间:2020-12-15 09:23:35 所属栏目:大数据 来源:网络整理
导读:我在很多例子中看到过创建一个与Result类型相同的变量,并在函数末尾分配它而不是仅仅使用Result变量. 例如,在System.JSON中的代码中 class function TJSONObject.ParseJSONValue( const Data: TArrayByte; const Offset: Integer; const ALength: Integer; O
我在很多例子中看到过创建一个与Result类型相同的变量,并在函数末尾分配它而不是仅仅使用Result变量.

例如,在System.JSON中的代码中

class function TJSONObject.ParseJSONValue(
  const Data: TArray<Byte>; 
  const Offset: Integer; 
  const ALength: Integer; 
  Options: TJSONParSEOptions
): TJSONValue;
var
  Parent: TJSONArray;
  Answer: TJSONValue;
  Br: TJSONByteReader;
begin
  Parent := TJSONArray.Create;
  Answer := nil; { Why not just use Result directly here? }
  Br := TJSONByteReader.Create(
          Data,Offset,ALength,TJSONParSEOption.IsUTF8 in Options
  );
  try
    ConsumeWhitespaces(Br);
    if 
      (ParseValue(Br,Parent,TJSONParSEOption.UseBool in Options) = ALength) 
      and
      (Parent.Count = 1)
    then
      Answer := Parent.Pop; { Why not just use Result directly here? }
    Result := Answer; 
  finally
    Parent.Free;
    Br.Free;
  end;
end;

为什么要创建变量Answer而不是仅仅使用Result?

这只是程序员决定这样做的方式还是背后的原因?

解决方法

Is this just the way the programmer decided to do it or is there a reason behind it?

这里没有充分的理由使用额外的局部变量.这样做只会增加复杂性.我会这样写:

class function TJSONObject.ParseJSONValue(
  const Data: TArray<Byte>; 
  const Offset: Integer; 
  const ALength: Integer; 
  Options: TJSONParSEOptions
): TJSONValue;
var
  Parent: TJSONArray;
  Br: TJSONByteReader;
begin
  Parent := TJSONArray.Create;
  try
    Br := TJSONByteReader.Create(
      Data,TJSONParSEOption.IsUTF8 in Options
    );
    try
      ConsumeWhitespaces(Br);
      if (ParseValue(Br,TJSONParSEOption.UseBool in Options) = ALength)
      and (Parent.Count = 1) then
        Result := Parent.Pop
      else
        Result := nil; 
    finally
      Br.Free;
    end;
  finally
    Parent.Free;
  end:
end;

这也纠正了生命周期管理和潜在的内存泄漏,如评论中所述.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读