c# - 为返回集合的方法设置为返回类型的最佳类型?

标签 c# .net

对于我们来说,返回集合的最佳类型是什么?

我应该使用 IList<T> 吗? , IEnumerable<T> , IQueryable<T> ,还有什么?哪个最好,为什么

我正在努力决定我应该在接口(interface)和我正在编写的几个类的实现中通常使用哪个。

编辑 让我进一步说明这一点,我正在使用 LINQ to SQL 通过 WCF 服务返回数据。感觉这可能会改变最佳使用类型?

最佳答案

Framework Design Guidelines 状态:

Use Collection<T> or a subclass of Collection<T> for properties or return values representing read/write collections.

public Collection<Session> Sessions { get; }

Use ReadOnlyCollection<T>, a subclass of ReadOnlyCollection<T>, or in rare cases IEnumerable<T> for properties or return values representing read-only collections.

public ReadOnlyCollection<Session> Sessions { get; }

In general, prefer ReadOnlyCollection<T>.

关于 LINQ,为 .NET 3.5 创建的指导方针很明确,但(imo)在理由上并不完全令人信服:

The review body made an explicit decision that LINQ should not change this guideline ["Do not return IEnumerator<T>, except as the return type of a GetEnumerator method"]. Your callers can end up with a clumsy object model if they choose not to use LINQ or a language that does not support it.

关于c# - 为返回集合的方法设置为返回类型的最佳类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1596579/

相关文章:

c# - 使用不同类型的节点从 JSON 创建类

javascript - 如何通过在 asp.net mvc 中更改下拉选项来过滤 html 表中的数据?

c# - 将 java 方法转换为 C# : converting bytes to integers with bit shift operators

c# - 如何在 C# 中以编程方式确定类型是否接受 null 值?

c# - BuildManager 解析页面继承

c# - 当 DoubleBuffered 设置为 true 时覆盖 OnPaint 的问题

c# - Entity Framework 批量插入抛出 KeyNotFoundException 错误

c# - WriteByte,如何使用

c# - 添加复选框列表后提交表单不再有效(.net mvc razor)

c# - 功能区控件专注于按钮单击