我使用的语言是C#.
正如我所读到的,如果一个对象的方法返回一个类似于列表的可枚举类型,最好将其签名声明为以下方式:
private IEnumerablelistOfNumbers() { // here goes the code of the method }
而不是
private ListlistOfNumbers() { // here goes the code of the method }
现在让我们想要作为参数传递A类型的对象列表.
当我们写作
private IEnumerablelistOfNumbers(List list) { // here goes the code of the method }
更容易访问列表的元素并使用它们进行任何计算而不是写入
private IEnumerablelistOfNumbers(IEnumerable list) { // here goes the code of the method. }
在第二种情况下,为了访问实现接口IEnumerable的列表元素,我们应该将列表转换为List,在方法的代码中.
我对作为参数实现IEnumerable接口的类型传递的最佳方式感到有点困惑.以上两者之间的最佳方法是什么?有没有更好的方法?
在此先感谢您的帮助.
这取决于您在方法中使用参数的方式.如果你要列举它,那么传球IEnumerable<T>
是一个不错的选择.如果您要添加/删除项目,那么它应该是IList<T>
,ICollection<T>
或List<T>
键入.
尽量不要给你的方法更多的知识,然后它需要履行它的责任.但也不要少给它知识,因为它将无法履行其职责:)
还有一个样本 - 您是否应该通过IList<T>
或者IEnumerable<T>
您的方法中是否需要计算项目?使用列表,您可以使用Count
属性.有了可枚举的Count()
扩展方法.正确的答案是 - 如果计数完全是您需要的,则通过项目计数.