接受int []和List <int>的方法

now*_*ed. 6 .net c#

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

我的答案涉及这样的事情:

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

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

任何想法如何签署方法?

Tim*_*ter 7

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

void TestMethod(IList<int> ints)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您仍然可以使用索引器或Count属性(是的,Count如果将数组转换为IList<T>或者,则数组具有属性ICollection<T>).这是两种类型之间最大可能的交集,允许快速访问,使用for-loops或其他支持的方法.

请注意,即使可以调用它们,也不支持某些方法Add,如果将NotSuportedException它与数组一起使用,您将在运行时获得("Collection具有固定大小").

  • 为了完整性,请记住`IList <int>`将允许你调用`.Add()`,如果传递`int []`而不是`List <int>`,将导致运行时异常. (2认同)