gpt4 book ai didi

c# - 接受 int[] 和 List 的方法

转载 作者:太空狗 更新时间:2023-10-29 20:58:32 26 4
gpt4 key购买 nike

问题:编写一个可以同时接受 List<int> 的方法声明和 int[]

我的回答是这样的:

void TestMethod(object param) // as object is the base class which can accept both int[] and List<int>

但这不是预期的答案,她是这么说的。

知道该方法签名会怎样吗?

最佳答案

您可以使用 IList<int> 这两个,int[]List<int>实现:

void TestMethod(IList<int> ints)

这样你仍然可以使用索引器或 Count property(是的,如果将数组转换为 CountIList<T>,则数组具有 ICollection<T> 属性)。这是两种类型之间最大可能的交集,允许快速访问,使用 for -循环或其他supported methods .

请注意,有些方法即使可以像 Add 一样调用,也不被支持。 ,你会得到一个 NotSuportedException在运行时(“Collection was a fixed size”)如果你将它与数组一起使用。

关于c# - 接受 int[] 和 List<int> 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27012805/

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