如何在构造中使用for创建枚举器? [英] How is Enumerator created with for in construction destroyed?

查看:97
本文介绍了如何在构造中使用for创建枚举器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从TCollection派生的集合,实现了GetEnumerator,因此我可以在lCollection中的lElem

I have a collection derived from TCollection, implementing GetEnumerator so I can use it in a construction like

for lElem in lCollection do

枚举器是从TObject派生的,就像Delphi提供的标准枚举器一样,因此不会有一个所有者。

The enumerator is derived from TObject, exactly like the standard enumerators supplied by Delphi and therefor doesn't have an owner.

Delphi帮助提到,如果枚举器支持IDisposable,它将被丢弃,但这当然仅适用于.NET。

The Delphi help mentions that if the enumerator supports IDisposable is it will be disposed of, but that is for .NET only of course.

我想知道的是,释放枚举器实例的方式和时间以及由谁释放?

What I was wondering is, how and when and by who the enumerator instance is freed?

推荐答案

对于每个for-enum语句,编译器都会生成与该伪代码大致对应的代码:

For each for-enum statement compiler generates code that roughly corresponds to this pseudocode:

enumerator := list.GetEnumerator;
try
  while enumerator.MoveNext do
    do something with enumerator.Current;
finally
  enumerator.Free;
end;

上面的代码是为作为类实例实现的枚举数生成的。如果将枚举数实现为接口,则最后一行不会调用.Free,而只是递减接口引用计数,以允许销毁它。

The code above is generated for enumerators that are implemented as class instances. If your enumerator is implemented as an interface, the last line would not call .Free but merely decrement interface reference count allowing it to be destroyed.

这篇关于如何在构造中使用for创建枚举器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆