gpt4 book ai didi

c# - 提供哪个参数类型是 IEnumerable 且具有 Count?

转载 作者:行者123 更新时间:2023-11-30 23:17:16 24 4
gpt4 key购买 nike

通常,可以优化提供接受数组的方法以接受更通用的类,这些类都是IEnumerable 并且需要CountLength .

示例:

public static T NextObject<T>(this Random random, T[] array)
{
return array[random.Next(array.Length)];
}

在这里,我使用 Array 获取特定元素,知道元素的数量。一般而言,哪个类别最适合此问题?

  • 列表
  • ICollection - 也有 Count
  • 其他接口(interface)或类或一组不同的接口(interface)?

认为IEnumerable 可能不是一个好主意,因为如果底层枚举器是 Count() 会对性能造成副作用更复杂。

最佳答案

您需要按索引和集合中的项目数访问项目。您还希望集合/界面中的额外成员更少

                      | IList<T> | ICollection<T> | IEnumerable<T> | T[]
Access by index | + | - | - | +
Count of items | + | + | - | +
Less unwanted members | - | + | + | ~

如您所见,ICollection 和 IEnumerable 不符合您的需要。我看不出选择 IList 或数组有什么大的区别。 IList 可能比数组更轻量级,但它有很多不需要的操作(添加、删除、清除),并且对于数组,您可以使用通常很方便的 params

关于c# - 提供哪个参数类型是 IEnumerable 且具有 Count?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41528421/

24 4 0