假设我有这样的方法(从 Jon Skeet 之前的 SO 回答中窃取):
public static IEnumerable<TSource> DuplicatesBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
// Yield it if the key hasn't actually been added - i.e. it
// was already in the set
if (!seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
在这种方法中,我有一个 HashSet 用于保存已看到的键。如果我在这样的事情中使用这种方法。
List<string> strings = new List<string> { "1", "1", "2", "3" };
List<string> somewhatUniques = strings.DuplicatesBy(s => s).Take(2);
这只会枚举字符串列表中的前两项。但是垃圾收集如何收集 seenKeys 哈希集。由于 yield 只是暂停了方法的执行,如果方法很昂贵,我怎么能确保我正确地处理东西?