6

我想将枚举器用于 Delphi XE2 的通用集合。我想知道,谁拥有函数 GetEnumerator 返回的 TEnumerator(我在文档中没有找到任何明确的答案):

  • 我是否拥有它并且需要在使用后释放它?
  • 还是它归收藏所有,我不必关心发布它?

代码:

procedure Test;
var
  myDictionary: TDictionary<String, String>;
  myEnum: TDictionary<String, String>.TPairEnumerator;
begin
  { Create a dictionary }
  myDictionary := TDictionary<String, String>.Create;
  myDictionary.Add('Key1', 'Value 1');
  myDictionary.Add('Key2', 'Value 2');

  { Use an enumerator }
  myEnum := myDictionary.GetEnumerator;
  // ... do something with the Enumerator ...

  { Release objects }
  myEnum.Free; // ** Do I need to free the enumerator? **
  myDictionary.Free;          
end;
4

1 回答 1

6

如果您查看 TDictionary 的源代码,您会发现 GetEnumerator(在其祖先中)调用 DoGetEnumerator,而在 TDictionary 中调用的是重新引入的 GetEnumerator 版本。

重新引入的 TDictionary.GetEnumerator 创建一个 TPairEnumerator 实例,将自身作为要枚举的字典传递。该字典不包含对 TPairEnumerator 的引用。PairEnumerator 不会收到关于其字典被破坏的通知。

所以,是的,您确实需要自己释放枚举器并避免任何访问冲突,您确实应该销毁它枚举的字典之前这样做。

于 2012-03-15T11:40:09.890 回答