gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:43:19 24 4
gpt4 key购买 nike

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

我应该使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com