哪你preFER的接口:T [],IEnumerable的< T&GT ;,的IList< T&GT ;,还是其他? [英] Which do you prefer for interfaces: T[], IEnumerable<T>, IList<T>, or other?

查看:129
本文介绍了哪你preFER的接口:T [],IEnumerable的< T&GT ;,的IList< T&GT ;,还是其他?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我希望整个社会将帮助我们解决了已经持续了一段时间工作场所的争论。这必须与定义,要么接受或者返回某种类型的列表界面。这样做有几种方式:

Ok, I'm hoping the community at large will aid us in solving a workplace debate that has been ongoing for a while. This has to do with defining interfaces that either accept or return lists of some type. There are several ways of doing this:

public interface Foo
{
	Bar[] Bars { get; }
	IEnumerable<Bar> Bars { get; }
	ICollection<Bar> Bars { get; }
	IList<Bar> Bars { get; }
}

我自己的preference是使用了IEnumerable的参数和数组返回值:

My own preference is to use IEnumerable for arguments and arrays for return values:

public interface Foo
{
	void Do(IEnumerable<Bar> bars);
	Bar[] Bars { get; }
}

我对这种做法的说法是,实现类可从IEnumerable的直接创建一个列表,轻松地与List.ToArray返回它()。但是有些人认为的IList应返回,而不是一个数组。我的问题是在这里,现在你需要再次返回之前它与一个ReadOnlyCollection还复制。返回的IEnumerable的选择似乎麻烦的客户端code?

My argument for this approach is that the implementation class can create a List directly from the IEnumerable and simply return it with List.ToArray(). However some believe that IList should be returned instead of an array. The problem I have here is that now your required again to copy it with a ReadOnlyCollection before returning. The option of returning IEnumerable seems troublesome for client code?

你用什么/ preFER? (特别是关于图书馆将组织外部使用其他开发者)

What do you use/prefer? (especially with regards to libraries that will be used by other developers outside your organization)

推荐答案

我的preference是的IEnumerable&LT; T&GT; 。任何其他建议的接口给出允许消费者修改基础集合的外观。这是几乎可以肯定不是你想做的事,因为它是使消费者能够悄无声息修改内部集合了什么。

My preference is IEnumerable<T>. Any other of the suggested interfaces gives the appearance of allowing the consumer to modify the underlying collection. This is almost certainly not what you want to do as it's allowing consumers to silently modify an internal collection.

另一个好恕我直言,是 ReadOnlyCollection还&LT; T&GT; 。它允许所有的乐趣.Count之间和索引属性,并毫不含糊地说,消费者不能修改我的数据。

Another good one IMHO, is ReadOnlyCollection<T>. It allows for all of the fun .Count and Indexer properties and unambiguously says to the consumer "you cannot modify my data".

这篇关于哪你preFER的接口:T [],IEnumerable的&LT; T&GT ;,的IList&LT; T&GT ;,还是其他?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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