它是不好的形式在C#返回数组?我应该返回列表< T&GT ;? [英] Is it bad form to return Arrays in C#? Should I return List<T>?

查看:127
本文介绍了它是不好的形式在C#返回数组?我应该返回列表< T&GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有它返回一个可变数目元素的功能,我应该返回一个数组或一个列表?在收藏的大小不会改变,一旦返回,也就是说所有的目的集合是不可改变的。我想只返回一个数组,但一些人说不要从一个函数返回可变大小的数组,因为它是穷形。不知道为什么?



不要紧,这需要在.NET 2.0兼容?


解决方案

这是不好的形式返回数组,如果没有必要,尤其是返回列表< T>



通常情况下,你会想要返回的IEnumerable< T> 的IList< T>



如果您的用户将只需要通过每个元素的运行,的IEnumerable< T> 将提供这种能力。它还允许你可能使用延迟执行实现例程(现在或以后)。



如果您的用户需要通过索引来访问元素,返回 IList的< T> 。这提供了所有的阵列的好处,但给你在你实现更大的灵活性。你可以实现它作为一个数组,列表,或其他一些集合实现的IList< T> ,你不必转换/复制到阵列<。 / p>

I have a function which returns a variable number of elements, should I return an array or a List? The "collection's" size does not change once returned, ie for all purposes the collection is immutable. I would think to just return an array, but some people have said to not return variable sized arrays from a function as it is "poor form". Not sure why?

Does it matter that this needs to be .NET 2.0 compliant?

解决方案

It's bad form to return arrays if not needed, and especially to return List<T>.

Usually, you'll want to return IEnumerable<T> or IList<T>.

If your user is going to just need to run through each element, IEnumerable<T> will provide this capability. It also allows you to potentially implement the routine (now or later) using deferred execution.

If your user needs to access elements by index, return IList<T>. This provides all of the benefits of arrays, but gives you more flexibility in your implementation. You can implement it as an array, a list, or some other collection that implements IList<T>, and you don't have to convert/copy to an array.

这篇关于它是不好的形式在C#返回数组?我应该返回列表&LT; T&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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