IEnumerable的< T>作为返回类型 [英] IEnumerable<T> as return type

查看:240
本文介绍了IEnumerable的< T>作为返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有用的问题的IEnumerable< T> 作为返回类型?
FxCop的抱怨返回列表< T> 。(它建议返回收藏< T> 代替)

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&LT; T&GT; 是一件坏事,但我该怎么办时,我想用懒惰检索?此外,收益关键字就是这样一个礼包。

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&LT; T&GT;

1) Is there inherently anything wrong with returning an IEnumerable<T>

没有什么都没有。事实上,如果你正在使用C#迭代器,这是预期的行为。将其转换为一个List&LT; T&GT;或其他集合类pre-先发制人是不是一个好主意。这样做是你发话人在使用模式的假设。我觉得这不是假设有关呼叫者的东西是一个好主意。他们可能有他们为什么要一个IEnumerable&LT好的理由; T&取代。也许他们想将其转换为一个完全不同的收集层次结构(在这种情况下,要列出一个转换是浪费)。

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)是否有在那里它可能是preferable返回其他的东西比的IEnumerable&LT任何情况下,T&GT;

2) Are there any circumstances where it may be preferable to return something other than IEnumerable<T>?

是的。虽然它不是一个伟大的想法,认为很多关于你的来电,这是完全没关系根据自己的行为做出决定。想象一下,你有一个多线程对象,这是请求排队到这是不断更新的对象的场景。在这种情况下,返回原始的IEnumerable&LT; T&GT;是不负责任的。只要集合被修改的枚举是无效,将导致发生execption。相反,你可以采取结构的快照,并返回该值。说,在一个List&LT; T&GT;形成。在这种情况下,我只想返回对象的直接结构(或接口)。

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的&LT; T&GT;作为返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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