gpt4 book ai didi

c# - 服务接口(interface)中的 IList、ICollection 或 IEnumerable?

转载 作者:太空狗 更新时间:2023-10-30 00:30:01 24 4
gpt4 key购买 nike

我正在使用 ASP.NET MVC 5 中的 Entity Framework 构建一个访问我的数据库的服务。所以我首先用他的界面编写一个基本服务。但我担心一件小事。

通常我返回 IEnumerable<T>在我的界面中,但这通常会导致 ToList()在代码中调用。

所以我想知道在这样的界面中返回什么最好。我可以返回 IList但恐怕它可能太多了,我不需要 IList 提供的所有方法。 .

这是我的代码:

public interface IBaseService<T>
{
T Add(T obj);
T Update(T obj);
T Remove(string id);
T Get(string id);

ICollection<T> Find(Expression<Func<bool, T>> func);
ICollection<T> GetAll();
}

最佳答案

你说的

Usually I return an IEnumerable in my interface, but that often leads to ToList() calls in the code.

你必须找出为什么你调用ToList()在结果上。您可能(但不太可能)想要修改结果(添加\删除项目)。从 Find 等方法返回可修改集合通常不是一个好的做法。或 GetAll , 但你可以返回 ICollection<T>IList<T> (如果您还需要通过索引器快速访问或在特定位置插入\删除)。

但是您调用 ToList 的可能性更大弄清楚那里有多少元素和/或访问特定元素。如果你只需要 Count - 返回 IReadOnlyCollection<T>延伸 IEnumerable<T>只有 Count属性(property)。如果您还需要通过索引器快速访问 - 返回 IReadOnlyList<T>延伸 IReadOnlyCollection<T>带索引器。

两者都是 ArrayList<T>实现所有这些接口(interface),这样您就可以按原样返回这些类:

 static IReadOnlyList<string> Test() {
return new string[0]; // fine
}

然而,返回时List这样 - 调用者可能会将其转换回 IList<T>并仍然修改它。这通常不是问题,但如果你想避免这种情况,请使用 AsReadOnly在列表中(它不会将任何内容复制到新列表中,所以不用担心性能):

static IReadOnlyList<string> Test() {
return new List<string>().AsReadOnly(); // not required but good practice
}

关于c# - 服务接口(interface)中的 IList、ICollection 或 IEnumerable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43201931/

24 4 0