您喜欢哪个接口:T [],IEnumerable< T>,IList< T>或其他? [英] Which do you prefer for interfaces: T[], IEnumerable<T>, IList<T>, or other?

查看:107
本文介绍了您喜欢哪个接口:T [],IEnumerable< T>,IList< T>或其他?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我希望整个社群能帮助我们解决一段时间内的工作场所争论。这与定义接受或返回某种类型的列表的接口有关。有以下几种方法:

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; }
}



我自己的偏好是使用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; }
}

这种方法的参数是实现类可以直接创建一个List从IEnumerable和简单地返回它与List.ToArray()。但有些人认为应该返回IList而不是数组。我在这里的问题是,现在你需要再次使用ReadOnlyCollection复制它,然后返回。返回IEnumerable的选项看起来麻烦的客户端代码?

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?

你使用/喜欢什么? (特别是对于您组织外其他开发者使用的库)

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

推荐答案

我的首选项是 IEnumerable< T> 。任何其他建议的界面给出允许消费者修改底层集合的外观。这几乎肯定不是你想要做的,因为它允许消费者静默修改内部集合。

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.

另一个很好的一个IMHO,是 ReadOnlyCollection< T> 。它允许所有有趣的.Count和Indexer属性,并明确地告诉消费者你不能修改我的数据。

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".

这篇关于您喜欢哪个接口:T [],IEnumerable&lt; T&gt;,IList&lt; T&gt;或其他?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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