IEnumerable<T>作为返回类型 [英] IEnumerable<T> as return type
问题描述
使用 IEnumerable
作为返回类型有问题吗?FxCop 抱怨返回 List
(它建议返回 Collection
代替).
Is there a problem with using IEnumerable<T>
as a return type?
FxCop complains about returning List<T>
(it advises returning Collection<T>
instead).
嗯,我一直遵循这样一条规则:接受最少的,但返回最多的."
Well, I've always been guided by a rule "accept the least you can, but return the maximum."
从这个角度来说,返回IEnumerable
是一件坏事,但是想使用懒惰检索"怎么办呢?此外,yield
关键字非常有用.
From this point of view, returning IEnumerable<T>
is a bad thing, but what should I do when I want to use "lazy retrieval"? Also, the yield
keyword is such a goodie.
推荐答案
这实际上是一个由两部分组成的问题.
This is really a two part question.
1) 返回一个 IEnumerable
1) Is there inherently anything wrong with returning an IEnumerable<T>
什么都没有.事实上,如果您使用 C# 迭代器,这就是预期的行为.将其转换为 List
No nothing at all. In fact if you are using C# iterators this is the expected behavior. Converting it to a List<T> or another collection class pre-emptively is not a good idea. Doing so is making an assumption on the usage pattern by your caller. I find it's not a good idea to assume anything about the caller. They may have good reasons why they want an IEnumerable<T>. Perhaps they want to convert it to a completely different collection hierarchy (in which case a conversion to List is wasted).
2) 是否有任何情况下返回 IEnumerable
2) Are there any circumstances where it may be preferable to return something other than IEnumerable<T>?
是的.虽然对呼叫者假设太多并不是一个好主意,但根据自己的行为做出决定是完全可以的.想象一个场景,您有一个多线程对象,它将请求排队到一个不断更新的对象中.在这种情况下,返回原始 IEnumerable<T>是不负责任的.一旦集合被修改,可枚举将失效并导致执行.相反,您可以拍摄结构的快照并返回该值.在列表中说
Yes. While it's not a great idea to assume much about your callers, it's perfectly okay to make decisions based on your own behavior. Imagine a scenario where you had a multi-threaded object which was queueing up requests into an object that was constantly being updated. In this case returning a raw IEnumerable<T> is irresponsible. As soon as the collection is modified the enumerable is invalidated and will cause an execption to occur. Instead you could take a snapshot of the structure and return that value. Say in a List<T> form. In this case I would just return the object as the direct structure (or interface).
不过这种情况肯定很少见.
This is certainly the rarer case though.
这篇关于IEnumerable<T>作为返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!