对于我们来说,返回集合的最佳类型是什么?
我应该使用 IList<T>
吗? , IEnumerable<T>
, IQueryable<T>
,还有什么?哪个最好,为什么?
我正在努力决定我应该在接口(interface)和我正在编写的几个类的实现中通常使用哪个。
编辑 让我进一步说明这一点,我正在使用 LINQ to SQL 通过 WCF 服务返回数据。感觉这可能会改变最佳使用类型?
最佳答案
Framework Design Guidelines 状态:
Use
Collection<T>
or a subclass ofCollection<T>
for properties or return values representing read/write collections.public Collection<Session> Sessions { get; }
Use
ReadOnlyCollection<T>
, a subclass ofReadOnlyCollection<T>
, or in rare casesIEnumerable<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 aGetEnumerator
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/