c# - 返回 IList<T> 是否比返回 T[] 或 List<T> 更糟糕?

标签 c# .net interface abstraction

此类问题的答案:List<T> or IList<T>似乎总是同意返回一个接口(interface)比返回一个集合的具体实现更好。但我正在努力解决这个问题。实例化一个接口(interface)是不可能的,所以如果你的方法返回一个接口(interface),它实际上仍然返回一个特定的实现。我通过编写 2 个小方法对此进行了一些试验:

public static IList<int> ExposeArrayIList()
{
    return new[] { 1, 2, 3 };
}

public static IList<int> ExposeListIList()
{
    return new List<int> { 1, 2, 3 };
}

并在我的测试程序中使用它们:

static void Main(string[] args)
{
    IList<int> arrayIList = ExposeArrayIList();
    IList<int> listIList = ExposeListIList();

    //Will give a runtime error
    arrayIList.Add(10);
    //Runs perfectly
    listIList.Add(10);
}

在这两种情况下,当我尝试添加一个新值时,我的编译器都没有给我任何错误,但显然是将我的数组公开为 IList<T> 的方法当我尝试向其中添加内容时出现运行时错误。 因此,不知道我的方法中发生了什么并且必须为其添加值的人被迫首先复制我的 IListList能够在不冒错误风险的情况下增加值(value)。当然,他们可以进行类型检查,看看他们是否正在处理 List。或 Array ,但如果他们不这样做,并且他们想将项目添加到集合中,他们别无选择来复制 IListList , 即使它已经是 List 。数组是否应该永远不会公开为 IList

我的另一个问题是基于 linked question 的公认答案。 (强调我的):

If you are exposing your class through a library that others will use, you generally want to expose it via interfaces rather than concrete implementations. This will help if you decide to change the implementation of your class later to use a different concrete class. In that case the users of your library won't need to update their code since the interface doesn't change.

If you are just using it internally, you may not care so much, and using List may be ok.

假设有人实际使用了我的 IList<T>他们从我的ExposeListIlist()方法就像添加/删除值一样。一切正常。但现在就像答案所暗示的那样,因为返回一个接口(interface)更灵活,我返回一个数组而不是一个列表(我这边没问题!),然后他们就可以请客了......

总而言之:

1) 暴露接口(interface)会导致不必要的转换?这不重要吗?

2) 有时如果库的用户不使用强制转换,当您更改方法时他们的代码可能会中断,即使该方法仍然完美无缺。

我可能想多了,但我没有得到普遍的共识,即返回接口(interface)比返回实现更可取。

最佳答案

也许这不能直接回答您的问题,但在 .NET 4.5+ 中,我更愿意在设计公共(public)或 protected API 时遵循这些规则:

  • 返回IEnumerable<T> , 如果只有枚举可用;
  • 返回IReadOnlyCollection<T>如果枚举和项目计数都可用;
  • 返回IReadOnlyList<T> , 如果枚举、项目计数和索引访问可用;
  • 返回ICollection<T>如果枚举、项目计数和修改可用;
  • 返回IList<T> , 如果枚举、项目计数、索引访问和修改可用。

最后两个选项假设,该方法不得返回数组为 IList<T>实现。

关于c# - 返回 IList<T> 是否比返回 T[] 或 List<T> 更糟糕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34334363/

相关文章:

c# - 使用 EPPlus 将 Excel 转换为 DataTable - excel 已锁定以供编辑

c# - 检查javascript的完整性,用户代码=服务器代码

Java - 两个具有相同方法的接口(interface),一个只是通用的

java - 获取泛型类型参数的正确方法

java - 执行 .class 文件的方法时如何断言安全?

c# - 无法修改“System.Collections.Concurrent.ConcurrentDictionary”的返回值

c# - 如何删除 xml "&"符号

c# - 如何检查文件当前是否打开或正在写入 .NET?

c# - EntityFramework where 子句是否始终按相同顺序返回对象

c# - 如何向 Windows 窗体元素添加动画?