c# - 对于接口(interface) : T[], IEnumerable<T>、IList<T> 或其他接口(interface),您更喜欢哪个?

标签 c# .net coding-style

好的,我希望整个社区能够帮助我们解决已经持续了一段时间的职场辩论。这与定义接受或返回某种类型列表的接口(interface)有关。有几种方法可以做到这一点:

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

我自己的偏好是使用 IEnumerable 作为参数,使用数组作为返回值:

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

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

您使用/喜欢什么? (特别是关于将由您组织外部的其他开发人员使用的库)

最佳答案

我的偏好是 IEnumerable<T> .任何其他建议的接口(interface)都提供了允许消费者修改基础集合的外观。这几乎肯定不是您想要做的,因为它允许消费者静默修改内部集合。

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

关于c# - 对于接口(interface) : T[], IEnumerable<T>、IList<T> 或其他接口(interface),您更喜欢哪个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1456132/

相关文章:

c# - 有没有办法在构建时注入(inject)代码?

c# - “Session”引发了 system.web.httpexception 类型的异常

c# - 低级对象上的 DependencyProperty/INotifyPropertyChanged

c# - Entity Framework Code First 场景中 ApplicationServices 连接字符串的用途是什么?

coding-style - 在编程时使用空格的最佳方法是什么?

java - 声明一堆相似变量的最少行数

c# - Azure表存储跨多个分区批量插入?

c# - 如何为 ref 传递的参数取消引用 ParameterType

c# - 没有 OrderedDictionary 的通用实现?

intellij-idea - PhpStorm中的行距