gpt4 book ai didi

c# - 使用 IReadOnlyCollection 而不是 IEnumerable 作为参数以避免可能的多重枚举

转载 作者:可可西里 更新时间:2023-11-01 09:12:45 25 4
gpt4 key购买 nike

我的问题与 this one 有关关于 IEnumerable<T> 的使用对比IReadOnlyCollection<T> .

我也一直使用 IEnumerable<T>将集合公开为返回类型和参数,因为它受益于不可变和延迟执行。

但是,我越来越担心我的代码中必须枚举参数以避免 ReSharper 可能给出的多重枚举警告的地方的激增。我理解 ReSharper 为什么建议这样做,并且我同意它建议的代码(如下)以确保封装(即,不假设调用者)。

 Foo[] arr = col as Foo[] ?? col.ToArray();

但是,我发现此代码的重复性具有污染性,并且我同意一些消息来源的观点 IReadOnlyCollection<T>是一个更好的选择,特别是在 this article 中提出的观点,其中指出:

Lately, I’ve been considering the merits and demerits of returning IEnumerable<T>.

On the plus side, it is about as minimal as an interface gets, so it leaves you as method author more flexibility than committing to a heavier alternative like IList<T> or (heaven forbid) an array.

However, as I outlined in the last post, an IEnumerable<T> return entices callers to violate the Liskov Substitution Principle. It’s too easy for them to use LINQ extension methods like Last() and Count(), whose semantics IEnumerable<T> does not promise.

What’s needed is a better way to lock down a returned collection without making such temptations so prominent. (I am reminded of Barney Fife learning this lesson the hard way.)

Enter IReadOnlyCollection<T>, new in .NET 4.5. It adds just one property to IEnumerable<T>: the Count property. By promising a count, you assure your callers that your IEnumerable<T> really does have a terminus. They can then use LINQ extension methods like Last() with a clear conscience.

然而,细心的人可能已经注意到,本文只讨论使用IReadOnlyCollection<T>。对于返回类型。我的问题是,同样的论点是否同样适用于将它用于参数?任何对此的理论想法或评论也将不胜感激。

事实上,我在考虑使用 IReadOnlyCollection<T> 的一般经验法则如果IEnumerable<T>,将是可能存在多重枚举的地方(相对于 ReSharper 警告)用来。否则,使用 IEnumerable<T> .

最佳答案

进一步思考后,根据我在问题中提到的文章,我得出结论,使用 IReadOnlyCollection<T> 确实可以。作为参数,但仅在肯定会被枚举的函数中。如果枚举是基于其他参数、对象状态或工作流的条件,那么它仍应作为 IEnumerable<T> 传入。以便在语义上确保惰性评估。

关于c# - 使用 IReadOnlyCollection<T> 而不是 IEnumerable<T> 作为参数以避免可能的多重枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41264238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com